skip to Main Content

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:
enter image description here

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


  1. Chosen as BEST ANSWER

    I followed this this tutorial and created a create a custom HttpActionResult

    public class CustomResult<TResultData> : IHttpActionResult
    {
        private readonly HttpRequestMessage _request;
        private readonly HttpStatusCode _httpStatusCode;
        private readonly TResultData _resultData;
    
        public CustomResult(HttpRequestMessage request, HttpStatusCode httpStatusCode, TResultData resultData)
        {
            _request = request;
            _httpStatusCode = httpStatusCode;
            _resultData = resultData;
        }
    
        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            var response = _request.CreateResponse(_httpStatusCode, _resultData);
            return Task.FromResult(response);
        }
    }
    

    I also created my own BaseApiController:

    public class MyBaseApiController : ApiController
    {
        protected IHttpActionResult NotFound<TResultData>(TResultData resultData)
        {
            return new CustomResult<TResultData>(Request, HttpStatusCode.NotFound, resultData);
        }
    
        protected IHttpActionResult ServerError<TResultData>(TResultData resultData)
        {
            return new CustomResult<TResultData>(Request, HttpStatusCode.InternalServerError, resultData);
        }
    }
    

    Now I can use the above base class to return json result with 404 status code:

    [RoutePrefix("error")]
    public class ErrorController : MyBaseApiController
    {
        [HttpGet]
        [Route("notfound")]
        public IHttpActionResult NotFoundMessage()
        {
            return NotFound(new { Message = "Not found", DocumentationUrl = "My documentation path" });
        }
    }
    

  2. 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)

    return Content(HttpStatusCode.NotFound, responseObjectInJson);
    

    Please bear in mind that in newer ASP.NET versions the Content does not have an overload which can accept StatusCode. In that case you can use the NotFound with any object and ASP.NET will serialize it on your behalf.

    return NotFound(responseObject);
    

    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 the ContentResult object directly

    return new ContentResult
    {
        Content = responseObjectInJson,
        ContentType = "application/json",
        StatusCode = (int)HttpStatusCode.NotFound
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search