简体   繁体   中英

How can I return a JSON object and status code (IHttpActionResult) from an ExceptionHandler in Web API?

Normally, I'd just do in my controller action:

return Content(System.Net.HttpStatusCode.InternalServerError, 
    new MyCustomObject("An error has occurred processing your request.", // Custom object, serialised to JSON automatically by the web api service
    ex.ToString()));`

However the Content method exists on the controller. The ExceptionHandler I made has this:

 public override void Handle(ExceptionHandlerContext context)
        {
            context.Result = ???;

The type of context.Result is IHttpActionResult , so what I need to do is create one and stick it in there. I can't find any constructors or similar that will allow me to create an IHttpActionResult outside of a controller. Is there an easy way?

I thing for custom responses you should probably implement your own http action result:

    public override void Handle(ExceptionHandlerContext context)
    {
        context.Result = new HttpContentResult(new { }, context.Request);
    }

    public class HttpContentResult : IHttpActionResult
    {
        private readonly object content;
        private readonly HttpRequestMessage requestMessage;

        public HttpContentResult(object content, HttpRequestMessage requestMessage)
        {
            this.content = content;
            this.requestMessage = requestMessage;
        }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            var httpContentResponse = new HttpResponseMessage(HttpStatusCode.BadRequest);
            var httpContent = new StringContent(content);
    
            //... [customize http contetnt properties]

            httpContentResponse.Content = httpContent;
            httpContentResponse.RequestMessage = this.requestMessage;

            //... [customize another http response properties]

            return Task.FromResult(httpContentResponse);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM