Response.Write() in WebService



我想在我的web服务方法中将JSON数据返回给客户端。一种方法是创建SoapExtension并将其用作我的web方法等的属性。另一种方法是简单地将[ScriptService]属性添加到web服务中,并让。net框架将结果作为{"d": "something"} JSON返回给用户(d在这里是我无法控制的东西)。但是,我想返回如下内容:

{"message": "action was successful!"}
最简单的方法可以是写一个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!"}}");
    }
}

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

{ "message": "action was successful!"} { "d": null}

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

服务器在发送HTTP报头后无法清除报头。

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

这个适合我:

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

你为什么不返回一个对象,然后在你的客户端你可以调用作为response.d ?

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

我使用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));
                    }
                });
            }

你的代码可以像这样(你需要允许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;
    }

在这个例子中,我使用了dictionary,但是你也可以使用任何带有message字段的对象。

如果我误解了你的意思,我很抱歉,但我真的不明白你为什么要做一个"回应"。写的东西。

希望我至少能帮到你。:)

最新更新