如何通过Asp.net WebAPI中的异常过滤器传递内容?
发布时间:2021-01-11 18:06:01 所属栏目:asp.Net 来源:互联网
导读:考虑以下代码: 我的问题是: 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传递: 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" } ); (编辑:莱芜站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- asp.net-mvc – asp.net mvc如何正确测试控制器
- asp.net-mvc – Url.RouteUrl返回null
- .net – 有人有一个例子,说明为什么我会主持一个
- 在ASP.NET Core中使用AOP来简化缓存操作
- asp.net-mvc – MVC 3布局页面,Razor模板和下拉列
- ASP.NET如何确定是否排队请求?
- asp.net-mvc – 如何将Model字段值传递给javascr
- asp.net-mvc-4 – .net 4.5 ASP.Net web API JSO
- asp.net-mvc – Gzip压缩无法运行ASP.net MVC5
- ASP.NET中读取XML文件信息的4种方法与示例代码
热点阅读