ASP.NET Web Api custom IHttpActionResult for HTTP Forbidden

by sunil ravulapalli /13. November 2013 06:06 /asp.net-web-api /Comments (0)
    public class ForbiddenActionResult : IHttpActionResult
    {
        private readonly HttpRequestMessage _request;
        private readonly string _reason;
        public ForbiddenActionResult(HttpRequestMessage request, string reason)
        {
            _request = request;
            _reason = reason;
        }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            var response = _request.CreateResponse(HttpStatusCode.Forbidden, _reason);
            return Task.FromResult(response);
        }
    }

You can use it like this:

public IHttpActionResult Get(long accountId)
{
    var payOffQuoteStatus = _payOffQuoteService.GetPayOffQuote(accountId);

    if (payOffQuoteStatus.IsEligibleForPayOffQuote)
          return Ok(payOffQuoteStatus.PayOffQuote);
    else
          return new ForbiddenActionResult(Request, payOffQuoteStatus.ReasonForIneligibility);
}
blog comments powered by Disqus