首页 asp.Net 如何通过Asp.net WebAPI中的异常过滤器传递内容?

如何通过Asp.net WebAPI中的异常过滤器传递内容?

考虑以下代码: 我的问题是: 1)我似乎无法将错误转发给HttpContent 2)我不能使用CreateContent扩展方法,因为context.Response.Content.CreateContent上不存在 这里的例子似乎只提供StringContent,我希望能够将内容作为JsobObject传递: http://www.asp.net/w

考虑以下代码:

我的问题是:

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

    }

解决方法

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

本文来自网络,不代表云浮站长网立场。转载请注明出处: https://www.0766zz.com/html/kaifa/asp-net/20210111/14398.html
上一篇
下一篇

作者: dawei

【声明】:云浮站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

为您推荐

返回顶部