【问题标题】:How can I return a JSON object and status code (IHttpActionResult) from an ExceptionHandler in Web API?如何从 Web API 中的 ExceptionHandler 返回 JSON 对象和状态代码 (IHttpActionResult)?
【发布时间】:2022-01-07 01:37:43
【问题描述】:

通常,我会在我的控制器操作中执行:

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()));`

但是Content 方法存在于控制器上。我做的 ExceptionHandler 有这个:

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

context.Result 的类型是IHttpActionResult,所以我需要做的是创建一个并将其粘贴在那里。我找不到任何可以让我在控制器之外创建IHttpActionResult 的构造函数或类似的东西。有什么简单的方法吗?

【问题讨论】:

标签: c# asp.net-web-api


【解决方案1】:

我喜欢自定义响应,您可能应该实现自己的 http 操作结果:

    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);
        }
    }

【讨论】:

    猜你喜欢
    • 2015-01-25
    • 2016-05-21
    • 1970-01-01
    • 1970-01-01
    • 2018-08-11
    • 2018-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多