Return a JSON string explicitly from Asp.net WEBAPI?

In Some cases I have NewtonSoft JSON.NET and in my controller I just return the Jobject from my controller and all is good.

But I have a case where I get some raw JSON from another service and need to return it from my webAPI. In this context I can't use NewtonSOft, but if I could then I'd create a JOBJECT from the string (which seems like unneeded processing overhead) and return that and all would be well with the world.

However, I want to return this simply, but if I return the string, then the client receives a JSON wrapper with my context as an encoded string.

How can I explicitly return a JSON from my WebAPI controller method?


There are a few alternatives. The simplest one is to have your method return a HttpResponseMessage , and create that response with a StringContent based on your string, something similar to the code below:

public HttpResponseMessage Get()
{
    string yourJson = GetJsonFromSomewhere();
    var response = this.Request.CreateResponse(HttpStatusCode.OK);
    response.Content = new StringContent(yourJson, Encoding.UTF8, "application/json");
    return response;
}

And checking null or empty JSON string

public HttpResponseMessage Get()
{
    string yourJson = GetJsonFromSomewhere();
    if (!string.IsNullOrEmpty(yourJson))
    {
        var response = this.Request.CreateResponse(HttpStatusCode.OK);
        response.Content = new StringContent(yourJson, Encoding.UTF8, "application/json");
        return response;
    }
    throw new HttpResponseException(HttpStatusCode.NotFound);
}

If you specifically want to return that JSON only, without using WebAPI features (like allowing XML), you can always write directly to the output. Assuming you're hosting this with ASP.NET, you have access to the Response object, so you can write it out that way as a string, then you don't need to actually return anything from your method - you've already written the response text to the output stream.

链接地址: http://www.djcxy.com/p/20424.html

上一篇: MVC:如何以JSON形式返回字符串

下一篇: 从Asp.net WEBAPI显式返回一个JSON字符串?