Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC5 - WebAPI 2 - CamelCase JSON formatter stopped working when Controller changed to return HttpResponseMessage

In our Web API 2 application, we configured the JSON formatting globally like this:

var jsonformatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;      
jsonformatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

This worked great - JSON was camelcase.., until we changed our controller methods to return a HttpReponseMessage (instead of the response model type directly) like this:

Request.CreateResponse(HttpStatusCode.OK, response);

That one change seemed to cause MVC to not use the JSON formatter. Our JSON is no longer CaemlCase.

Is this the expected/designed behavior or have I not specified the formatter correctly?

Thanks, -Mike

like image 725
HokieMike Avatar asked May 16 '14 20:05

HokieMike


People also ask

Which line of code can you use to format JSON data in camel case?

If you want JsonSerializer class to use camel casing you can do the following: var options = new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy. CamelCase }; string json = JsonSerializer. Serialize(empList, options); return Ok(json);

Can we return Web API controller view?

You don't return a View from an API controller. But you can return API data from an MVC controller. The solution would be to correct the errors, not try to hack the API controller. Constructor arguments most certainly can be used in controllers for dependency injection.

How return only JSON from ASP Net Web API service irrespective of the Accept header value?

How to return only JSON from ASP.NET Web API service. Now whenever we are going to request the service is always going to format the data using JSON Formatter irrespective of the acceptheader value in the request. You can use this in service when it only supports JSON data. So build the solution and run the app.


1 Answers

Actual method that is called when you use Request.CreateResponse is this:

public static HttpResponseMessage CreateResponse<T>(
                                          this HttpRequestMessage request, T value)
{
    return request.CreateResponse<T>(HttpStatusCode.OK, value, configuration: null);
}

As you see configuration property is just being set to null.

So you can just manually take configuration from Request object and call another overload like this:

Request.CreateResponse(HttpStatusCode.OK, response, Request.GetConfiguration());

If you are interested in more detail, you can check source code of the framework. CreateResponse is defined here

like image 93
SoftwareFactor Avatar answered Oct 06 '22 00:10

SoftwareFactor