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
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);
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 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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With