Reputation: 5946
I'm tying to get a nice and simple API with setting status-code and get the documentation of swagger (swashbuckle)
First, my controller looked like this:
public class ValuesController : ControllerBase
{
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(List<Value>))]
[HttpGet, System.Web.Mvc.Route("api/values/")]
public async Task<List<Value>> GetValues(HttpRequestMessage request)
{
using (DatabaseContext context = new DatabaseContext())
{
return await context.Values.Take(10).ToListAsync();
}
}
}
All fine, Swagger shows the result json-formatted. Problem is, I can't set the status code (like, if database-error I could set to Err 500 or s.th.).
Here I read, for setting a status code we need to return a HttpResponseMessage
So I modified my code:
public class ValuesController : ControllerBase
{
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(HttpResponseMessage))]
[HttpGet, System.Web.Mvc.Route("api/values/")]
public async Task<HttpResponseMessage> GetValues(HttpRequestMessage request)
{
using (DatabaseContext context = new DatabaseContext())
{
var valuesToReturn = await context.Values.Take(10).ToListAsync();
return request.CreateResponse(HttpStatusCode.NotModified, valuesToReturn);
}
}
}
Now, the status code is set correctly, but swagger doesn't show any result.
So, I thought this maybe is a swagger-problem.
Next step was to test the API with Chromes Boomerang-Plugin, but same: Status-Code is 304, but the body (result/content) is empty:
Any idea on how to set the body correctly with the HttpResponseMessage?
Or, any idea on how to set the status code in the api-method when return value is e.g. List<Value>
?
Upvotes: 1
Views: 5139
Reputation: 114
At first the HTTP status code 304 doesn't have a body. The 304 response MUST NOT contain a message-body, and thus is always terminated by the first empty line after the header fields.
Just change the status code.
Upvotes: 3
Reputation: 6965
var valuesToReturn = new List<string>();
valuesToReturn.Add("test01");
var res = new HttpResponseMessage()
{
Content = new StringContent(JsonConvert.SerializeObject(valuesToReturn), Encoding.UTF8, "application/json"),
StatusCode = HttpStatusCode.Redirect
};
return res;
Upvotes: 0
Reputation: 125
Rawitas Krungkaews answer is partly correct.
But, you should use the generic ObjectContent
instead of StringContent
:
var res = new HttpResponseMessage()
{
Content = new ObjectContent<List<Value>>(valuesToReturn, DefaultJsonFormatter),
StatusCode = HttpStatusCode.Redirect
};
return res;
The parameter Default
is the MediaTypeFormatter. I think you can declare it in your class like:
private static readonly MediaTypeFormatter DefaultJsonFormatter
= new JsonMediaTypeFormatter();
Upvotes: 2