Web API 2 returns text / simple responses

In fact, I'm struggling with something, which I hope people can help here. I am writing a RESTful API in Web API 2. Whenever I submit a request to this service, the response is sent sequentially with the Content-Type from text/plain . Obviously this is not good, my answer should be Content-Type of application/json . I tried a few suggestions that I found on Google, but I don’t think I understand the whole picture.

Is there anything special I need to do in order for my web service to respond to application/json content? Please note that I want this to work globally throughout the application, so I cannot change this answer and set its content type. I want this to be the default behavior for the entire web service: if the request contains an Accept header for application/json I want my web service to return this Content-Type instead of text/plain .

Edit to clarify:

My answer contains an object called "responseData" that needs to be serialized in JSON and included in the body. I am now compiling my answer as follows:

 HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, responseData); return response; 

responseData is a POCO. This is correctly serialized as JSON and returned in response - the only missing part is the Content-Type, which is incorrectly set to "text / plain". I could manually change this with every single answer I compose, but I want to configure it globally.

+6
source share
3 answers

OK, assuming your responseData is a string, the Content-type header will be text/plain when creating the HttpResponseMessage . It does not matter what the contents of the string are, since no attempt is made to determine this.

The solution is to create the appropriate Content object for your message, initialized with the return media type:

 HttpResponseMessage response = new HttpResponseMessage() { Content = new StringContent( responseData, Encoding.UTF8, "application/json" ) }; 

There are other methods that return a specific type of object and allow the API libraries to be serialized in JSON or XML for you as needed. I prefer the infrastructure to do the work for me wherever possible, but this is how you will achieve this with the line you created yourself.


For a rigorous JSON-only result, remove the XML formatter from the WebAPI configuration and return POCO.

In App_Start\WebApiConfig.cs add the following to the WebApiConfig.Register method:

 config.Formatters.Remove(config.Formatters.XmlFormatter); 

And for your API:

 public class MyObject { public bool result; public string reason; } public class TestController : ApiController { public MyObject GetData() { MyObject result = new MyObject { result = "true", reason = "Testing POCO return" }; return result; } } 

I ran this and requested /api/Test from Chrome, which doesn't even mention application/json in the Accept header. Here are the response headers until they reach the Content-type :

 HTTP/1.1 200 OK Cache-Control: no-cache Pragma: no-cache Content-Type: application/json; charset=utf-8 

And the body:

 {"result":true,"reason":"Testing POCO return"} 

Since I disabled XML, it was JSON by default.

+7
source

Add the following to the Global.asax file.

 protected void Application_Start() { JsonSerializerSettings serializerSettings = new JsonSerializerSettings(); serializerSettings.Converters.Add(new IsoDateTimeConverter()); var jsonFormatter = new JsonNetFormatter(serializerSettings); jsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); GlobalConfiguration.Configuration.Formatters.Insert(0, jsonFormatter); } 
0
source

Another possible source of the described problem is that the game may have authorization redirection, as it was for us, when one of the engineers decided to reuse user authentication for api.

This means that incoming requests are redirected to the login page, which was a text/html response that could not be parsed using ReadAsync<> . Stupidly mistaken, but not easy to notice.

The solution in this case was to remove user authentication and implement HMAC-based authentication for api.

0
source

Source: https://habr.com/ru/post/971084/


All Articles