Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

asp.net - Response.Write() in WebService

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}

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:

Server cannot clear headers after HTTP headers have been sent.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This works for me:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...