bsayegh
bsayegh

Reputation: 1000

Globally formatting .net Web Api response

I have a Web Api service that retrieves data from another service, which returns Json. I don't want to do anything to the response, I just want to return it directly to the client.

Since the response is a string, if I simply return the response, it contains escape characters and messy formatting. If I convert the response in to an object, the WebApi will use Json.Net to automatically format the response correctly.

 public IHttpActionResult GetServices()
    {
        var data =  _dataService.Get(); //retrieves data from a service
        var result = JsonConvert.DeserializeObject(data); //convert to object

        return Ok(result);

    }

What I would like is to either A: Be able to return the exact string response from the service, without any of the escape characters and with the proper formatting, or B: Set a global settings that will automatically Deserialize the response so that the Web Api can handle it the way I am doing it already.

On Startup I am setting some values that describe how formatting should be handled, but apparently these aren't correct for what im trying to do.

        HttpConfiguration configuration = new HttpConfiguration();
        var settings = configuration.Formatters.JsonFormatter.SerializerSettings;
        settings.Formatting = Formatting.Indented;
        settings.ContractResolver = new DefaultContractResolver();

Do I need to create a custom ContractResolver or something? Is there one that already handles this for me?

Thanks

Upvotes: 0

Views: 147

Answers (1)

Nkosi
Nkosi

Reputation: 247018

If you want to just pass through the json (Option A), you can do this

public IHttpActionResult GetServices() {
    var json = _dataService.Get(); //retrieves data from a service
    HttpContent content = new System.Net.Http.StringContent(json, Encoding.UTF8, "application/json");
    var response = Request.CreateResponse(HttpStatusCode.OK);
    response.Content = content;
    return ResponseMessage(response);
}

Upvotes: 1

Related Questions