【问题标题】:How to make a HTTP request using c# to asmx web-method which is returning Context.Response.Write?如何使用 c# 向返回 Context.Response.Write 的 asmx web-method 发出 HTTP 请求?
【发布时间】:2017-03-12 08:21:39
【问题描述】:

我在 asmx Web 服务中创建了一个 Web 方法,它使用 Context.Resopnse.Write 返回纯 JSON。

现在上面的行会将json数据写入请求的连接管道,但是如何接受来自作为web服务客户端的c#函数的响应。

这是我的网络服务方法:

[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));
}

这里是客户端函数:

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

这里下面两行不起作用,因为它是一个 void 类型的返回方法,当我返回字符串而不是使用上下文时,下面的代码将起作用。

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

我认为应该是这样的:

String jsonstring =  Context.Request(obj.GetAllEmployeesFromEmpInPureJSON())

【问题讨论】:

    标签: c# web-services


    【解决方案1】:

    您可以像这样使用 HttpClient 使用此服务:

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

    为了让它发挥作用,我必须做几件事:

    • 按照this question 的描述将协议添加到服务的 web.config。
    • [ScriptMethod(UseHttpGet = true)]替换现有的ScriptMethod属性

    【讨论】:

    • 你这样做有什么意义。如果我想要这种方式,那么我只需在客户端本身中创建一个函数并调用它。这里有什么用网络方法。我希望客户端在 ajax 调用接收数据时接收数据,或者像 HttpClient 那样创建连接并可以传递和接收数据。
    • 处理程序将在请求时向用户发送数据。例如,一个处理程序可以被称为“image.src =”ImageHandler.ashx?id=1”,它会返回 context.response。我认为应该有一些类似的方式
    • 对不起,我误解了这个问题。我已经更改了我的答案,包括一个如何使用 HttpClient 从您的服务中获取 Json 的示例
    猜你喜欢
    • 1970-01-01
    • 2019-10-02
    • 2019-03-05
    • 2018-09-15
    • 2018-03-12
    • 2023-03-07
    • 2011-12-03
    • 1970-01-01
    • 2019-10-20
    相关资源
    最近更新 更多