Return a JSON string explicitly from Asp.net WEBAPI? Return a JSON string explicitly from Asp.net WEBAPI? json json

Return a JSON string explicitly from Asp.net WEBAPI?


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


Here is @carlosfigueira's solution adapted to use the IHttpActionResult Interface that was introduced with WebApi2:

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


sample example to return json data from web api GET method

[HttpGet]public IActionResult Get(){            return Content("{\"firstName\": \"John\",  \"lastName\": \"Doe\", \"lastUpdateTimeStamp\": \"2018-07-30T18:25:43.511Z\",  \"nextUpdateTimeStamp\": \"2018-08-30T18:25:43.511Z\");}