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

Categories

0 votes
1.2k 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...