WebService中的Response.Write() [英] Response.Write() in WebService

查看:327
本文介绍了WebService中的Response.Write()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过Web服务方法将JSON数据返回给客户端.一种方法是创建SoapExtension并将其用作Web方法等的属性.另一种方法是将[ScriptService]属性简单地添加到Web服务,然后让.NET Framework将结果返回为{"d": "something"} JSON,然后给用户(d超出了我的控制范围).但是,我想返回类似的内容:

I want to return JSON data back to the client, in my web service method. One way is to create SoapExtension and use it as attribute on my web method, etc. Another way is to simply add [ScriptService] attribute to the web service, and let .NET framework return the result as {"d": "something"} JSON, back to the user (d here being something out of my control). However, I want to return something like:

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

最简单的方法可能是编写如下的网络方法:

The simplest approach could be writing a web method like:

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

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

This way, what I'll get at client is:

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

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

Which means that ASP.NET is appending its success result to my JSON result. If on the other hand I flush the response after writing the success message, (like response.Flush();), the exception happens that says:

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

Server cannot clear headers after HTTP headers have been sent.

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

So, what to do to just get my JSON result, without changing the approach?

推荐答案

这对我有用:

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

这篇关于WebService中的Response.Write()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆