WebService中的Response.Write()

Sae*_*ati 9 asp.net json web-services asmx

我想在我的Web服务方法中将JSON数据返回给客户端.一种方法是SoapExtension在我的Web方法等上创建和使用它作为属性.另一种方法是简单地将[ScriptService]属性添加到Web服务,并让.NET框架将结果作为{"d": "something"}JSON返回给用户(d这里是我的控制).但是,我想要返回类似的内容:

{"message": "action was successful!"}
Run Code Online (Sandbox Code Playgroud)

最简单的方法是编写一个Web方法,如:

[WebMethod]
public static void StopSite(int siteId)
{
    HttpResponse response = HttpContext.Current.Response;
    try
    {
        // Doing something here
        response.Write("{{\"message\": \"action was successful!\"}}");
    }
    catch (Exception ex)
    {
        response.StatusCode = 500;
        response.Write("{{\"message\": \"action failed!\"}}");
    }
}
Run Code Online (Sandbox Code Playgroud)

这样,我将在客户端得到的是:

{ "message": "action was successful!"} { "d": null}
Run Code Online (Sandbox Code Playgroud)

这意味着ASP.NET将其成功结果附加到我的JSON结果.另一方面,如果我在写完成功消息后刷新响应(如response.Flush();),则会发生以下异常:

发送HTTP标头后,服务器无法清除标头.

那么,如何在不改变方法的情况下获取我的JSON结果呢?

Sev*_*in7 12

这对我有用:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void ReturnExactValueFromWebMethod(string AuthCode)
{
    string r = "return my exact response without ASP.NET added junk";
    HttpContext.Current.Response.BufferOutput = true;
    HttpContext.Current.Response.Write(r);
    HttpContext.Current.Response.Flush();
}
Run Code Online (Sandbox Code Playgroud)

  • 这几行帮助了我,但对我来说,我添加了这些行以使其工作 Response.Flush(); Response.End(); (2认同)
  • ResponseEnd()导致"线程被中止"这对我有用!HttpContext.Current.Response.Flush(); HttpContext.Current.Response.SuppressContent = true; HttpContext.Current.ApplicationInstance.CompleteRequest(); http://stackoverflow.com/questions/20988445/how-to-avoid-response-end-thread-was-being-aborted-exception-during-the-exce (2认同)

Jen*_*nha 2

为什么不返回一个对象,然后在客户端中调用 as response.d

我不知道你如何调用你的网络服务,但我做了一个例子,做了一些假设:

我用 jquery ajax 做了这个例子

function Test(a) {

                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "TestRW.asmx/HelloWorld",
                    data: "{'id':" + a + "}",
                    dataType: "json",
                    success: function (response) {
                        alert(JSON.stringify(response.d));

                    }
                });
            }
Run Code Online (Sandbox Code Playgroud)

您的代码可能如下所示(您需要首先允许从脚本调用 Web 服务:“[System.Web.Script.Services.ScriptService]”):

    [WebMethod]
    public object HelloWorld(int id)
    {
        Dictionary<string, string> dic = new Dictionary<string, string>();
        dic.Add("message","success");

        return dic;
    }
Run Code Online (Sandbox Code Playgroud)

在此示例中,我使用了字典,但您可以使用带有“消息”字段的任何对象。

如果我误解了你的意思,我很抱歉,但我真的不明白你为什么要做“response.write”的事情。

希望我至少有所帮助。:)