【问题标题】:Response.Write() in WebServiceWebService 中的 Response.Write()
【发布时间】:2012-01-22 22:41:51
【问题描述】:

我想在我的 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 结果?

【问题讨论】:

  • 尝试设置 response.BufferOutput = true;

标签: asp.net json web-services asmx


【解决方案1】:

您为什么不返回一个对象,然后在您的客户端中调用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;
    }

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

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

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

【讨论】:

    【解决方案2】:

    这对我有用:

    [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.Flush(); Response.End();
    • ResponseEnd() 导致“线程被中止” 这对我有用! HttpContext.Current.Response.Flush(); HttpContext.Current.Response.SuppressContent = true; HttpContext.Current.ApplicationInstance.CompleteRequest(); stackoverflow.com/questions/20988445/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-02
    • 2013-05-09
    • 2010-10-29
    • 1970-01-01
    • 2011-08-29
    相关资源
    最近更新 更多