0

I created a web method in asmx web services and it is returning pure JSON using Context.Resopnse.Write.

Now the above line will write json data to the connection pipeline of the request but how to accept the response from c# function which is acting as a client to the web-service.

Here is my web-service method:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void GetAllEmployeesFromEmpInPureJSON()
{
    SqlConnection vConn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString);
    vConn.Open();
    String vQuery = "Select * from Employee";
    SqlDataAdapter vAdap = new SqlDataAdapter(vQuery, vConn);
    DataSet vDs = new DataSet();
    vAdap.Fill(vDs, "Employee");
    vConn.Close();
    DataTable vDt = vDs.Tables[0];
    Context.Response.Write(JsonConvert.SerializeObject(vDt));
}

Here is the client function:

protected void Button1_Click(object sender, EventArgs e)
{
    Lab25WebServiceSoapClient obj = new Lab25WebServiceSoapClient();
    DataTable vDt = new DataTable();

    //String jsonstring = obj.GetAllEmployeesFromEmpInPureJSON();
    //vDt = JsonConvert.DeserializeObject(jsonstring) as DataTable;
    GridView1.DataSource = vDt;
    GridView1.DataBind();
}

Here the below two lines don't work because it is a void type return method and below code will work when I am returning string instead of using context.

String jsonstring = obj.GetAllEmployeesFromEmpInPureJSON();
vDt = JsonConvert.DeserializeObject(jsonstring) as DataTable;

I think there should be something like:

String jsonstring =  Context.Request(obj.GetAllEmployeesFromEmpInPureJSON())
Nithin B
  • 601
  • 1
  • 9
  • 26

1 Answers1

0

You can consume this service using HttpClient like this:

HttpClient httpClient = new HttpClient();
string result = httpClient.GetStringAsync("<domain>/Lab25WebService.asmx/GetAllEmployeesFromEmpInPureJSON").Result;

To get this to work I had to do a couple of things:

  • Add protocols to the web.config of the service as this question describes.
  • Replace the existing ScriptMethod attribute with [ScriptMethod(UseHttpGet = true)]
Community
  • 1
  • 1
res10
  • 146
  • 7
  • What is your point of doing this. If I want this way then I would just create a function in client itself and call it. Here what is the use of having web-method. I want client to receive as the ajax call receives data or like HttpClient which will create a connection and can pass and receive data. – Nithin B Mar 12 '17 at 10:16
  • An handler will send data to user when it requested. For example an handler can be called like " image.src = "ImageHandler.ashx?id=1" and it will return context.response. I am thinking there should be some way similar to this – Nithin B Mar 12 '17 at 10:22
  • Sorry I misinterpreted the question. I've changed my answer to include an example of how HttpClient could be used to get the Json from your service – res10 Mar 12 '17 at 13:52