Saturday, September 12, 2015

Custom NotFound() result in WebAPI 2



WebAPI 2.X supports IHttpActionResult which supports return type which more relevant to HTTP verbs. Like, we can Return Ok() to return result along 200 status code. If the resource is not found we can return NotFound() which will return 400 status code from service.

But, Did you notice that there is no overloaded NotFound() function which can carry some message to client in need ?

As solution, we can define our own class by inheriting IHttpActionResult to it. In this example, we have defined NotFound class which takes two parameter as default in its constructor. So, it will allow us to return some message along with 400 status code.

public class NotFound : IHttpActionResult
    {
        public NotFound(string message, HttpRequestMessage request)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            Message = message;
            Request = request;
        }

        public string Message { get; private set; }

        public HttpRequestMessage Request { get; private set; }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            return Task.FromResult(Execute());
        }

        public HttpResponseMessage Execute()
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.NotFound);
            response.Content = new StringContent(Message); // Put the message in the response body (text/plain content).
            response.RequestMessage = Request;
            return response;
        }
    }


Now, we can use this to return NotFound() with message. 


public class TestController : ApiController
    {
        public IHttpActionResult Get()
        {
            return new NotFound("Though it found but looks like not found", Request);
        }
    }



No comments:

Post a Comment