【问题标题】:How to pass content in response from Exception filter in Asp.net WebAPI?如何传递内容以响应 Asp.net WebAPI 中的异常过滤器?
【发布时间】:2026-02-23 08:00:01
【问题描述】:

考虑以下代码:

我的问题是:

1) 我似乎无法将错误转换为 HttpContent

2) 我不能使用 CreateContent 扩展方法,因为它在 context.Response.Content.CreateContent 中不存在

这里的示例似乎只提供 StringContent,我希望能够将内容作为 JsobObject 传递: http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling

 public class ServiceLayerExceptionFilter : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext context)
        {
            if (context.Response == null)
            {                
                var exception = context.Exception as ModelValidationException;

                if ( exception != null )
                {
                    var modelState = new ModelStateDictionary();
                    modelState.AddModelError(exception.Key, exception.Description);

                    var errors = modelState.SelectMany(x => x.Value.Errors).Select(x => x.ErrorMessage);

                    // Cannot cast errors to HttpContent??
                    // var resp = new HttpResponseMessage(HttpStatusCode.BadRequest) {Content = errors};
                    // throw new HttpResponseException(resp);

                    // Cannot create response from extension method??
                    //context.Response.Content.CreateContent
                }
                else
                {
                    context.Response = new HttpResponseMessage(context.Exception.ConvertToHttpStatus());
                }                
            }

            base.OnException(context);
        }

    }

【问题讨论】:

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


    【解决方案1】:
    context.Response = new HttpResponseMessage(context.Exception.ConvertToHttpStatus());
    context.Response.Content = new StringContent("Hello World");
    

    如果您想传递复杂的对象,您还可以使用CreateResponse(在RC 中添加以替换不再存在的通用HttpResponseMessage<T> 类)方法:

    context.Response = context.Request.CreateResponse(
        context.Exception.ConvertToHttpStatus(), 
        new MyViewModel { Foo = "bar" }
    );
    

    【讨论】:

    • 抱歉,请参阅我帖子中的上述链接。我想创建 JsonObject 类型的内容。
    • 太好了,我错过了“使用 System.Net.Http”。谢谢!