How to make a HTTP request using c# to asmx web-method which is returning Context.Response.Write?

北慕城南 提交于 2019-12-25 09:06:15

问题


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())

回答1:


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)]


来源:https://stackoverflow.com/questions/42745264/how-to-make-a-http-request-using-c-sharp-to-asmx-web-method-which-is-returning-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!