I am using ASP.NET Web API 2 and I want to return a json result from my API with the error code 404.
I am trying to mimic this result:
This is what I have tried:
[RoutePrefix("error")]
public class ErrorController : ShoplessBaseApiController
{
[HttpGet]
[Route("notfound")]
public IHttpActionResult NotFoundMessage()
{
return MyNotFound(new { Message = "Not douns", DocumentationUrl = "My documentation path" });
}
protected IHttpActionResult MyNotFound<T>(T t)
{
return Content(HttpStatusCode.NotFound, JsonConvert.SerializeObject(t));
}
}
The above returns a serialized json but the problem is that the content type is not json.
I want to return something like this:
[HttpGet]
[Route("notfound")]
public IHttpActionResult NotFoundMessage()
{
return Json(new { Message = "Not found", DocumentationUrl = "My documentation path" });
}
but the problem is, Json does not accept the status code and returns 200
2
Answers
I followed this this tutorial and created a create a custom HttpActionResult
I also created my own BaseApiController:
Now I can use the above base class to return json result with 404 status code:
In case of ASP.NET WebAPI you can use
Content
for that.Content
‘s first parameter is the status code and the second is a string (already serialized response body)Please bear in mind that in newer ASP.NET versions the
Content
does not have an overload which can acceptStatusCode
. In that case you can use theNotFound
with any object and ASP.NET will serialize it on your behalf.UPDATE #1
I’ve overlooked that part where you have stated that the content-type is not set. You can set it if you are not using the
Content
method rather than theContentResult
object directly