我想通过我的Web服务方法将JSON数据返回给客户端。一种方法是创建SoapExtension
并将其用作我的Web方法等的属性。另一种方法是简单地将[ScriptService]
属性添加到Web服务,然后让.NET Framework将结果作为{"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();
),则会发生异常消息:Server cannot clear headers after HTTP headers have been sent.
那么,如何在不改变方法的情况下仅获取我的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();
}
关于asp.net - Web服务中的Response.Write(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8550530/