1

I'm really confused about the most appropriate way to return responses for my RESTful API that I'm building using Web API 2.

At first I made my actions return IHttpActionResult and in the method I would use return Ok() or return NotFound() etc.

Then I found there was no Forbidden() so I thought I must be doing things wrong. So now I'm making my actions return HttpResponseMessage. In my code I'm returning a response by doing the following:

HttpResponseMessage response = Request.CreateResponse();
response.StatusCode = HttpStatusCode.OK;
response.Content = new StringContent(JsonConvert.SerializeObject(responseData));
return response;

The problem is, this response now gets sent with the Content-Type "text/plain" - it needs to be sent with the Content-Type of "application/json". I can't find how I'm supposed to alter the Content-Type of the response, but even if I could it seems cumbersome to do this with every request. Is the a better way, some sort of best practice that I'm overlooking here?

3 Answers 3

2

Instead of populating it manually, you can do this

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

This, this will return content type as json.

Sign up to request clarification or add additional context in comments.

1 Comment

I wrote my own answer and then realised it was almost identical to yours... Request.CreateResponse does indeed change it from text/plain to application/json (or rather it uses the media formatter). I would add this link where I found the answer: Action Results in Web API 2
0

You can set content negotiation for each request by modifying a collection in global.asax

Comments

0

Have you set the JsonFormatter in your global.asax? For example:

GlobalConfiguration.Configuration.EnsureInitialized();
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new DefaultContractResolver();

Another issue which I found is that your routing prefix / route with parameters signature on your Controller cannot be match with the Url you passing in giving usually 404 code.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.