Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 299
Saeed Neamati Avatar asked Dec 18 '11 07:12

Saeed Neamati


1 Answers

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();
}
like image 147
Sevin7 Avatar answered Sep 19 '22 15:09

Sevin7