如何通过Asp.net WebAPI中的异常过滤器传递内容?
发布时间:2020-12-15 20:02:31 所属栏目:asp.Net 来源:网络整理
导读:考虑以下代码: 我的问题是: 1)我似乎无法将错误转发给HttpContent 2)我不能使用CreateContent扩展方法,因为context.Response.Content.CreateContent上不存在 这里的例子似乎只提供StringContent,我希望能够将内容作为JsobObject传递: http://www.asp.net/
考虑以下代码:
我的问题是: 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中的当前应用程序虚拟路径
- asp.net – Microsoft Report Viewer 2010部署
- asp.net-mvc – 在foreach中的mvc radiobuttons
- asp.net – 从域到www.domain的全局301重定向
- asp.net core系列 38 WebAPI 返回类型与响应格式--必备
- asp.net – 在ValidationSummary上动态显示bootstrap的周围
- asp.net – 使用Visual Studio发布Web App项目
- asp.net-mvc – 如何在RouteTable MVC.Net中手动查找路由?
- 是否有必要创建ASP.NET 4.0 SQL会话状态数据库,与现有的ASP
- asp.net-mvc – 在ServiceStack服务上进行身份验证后访问客
推荐文章
站长推荐
- 如何在不使用角色的情况下使用ASP.NET WebAPI实现
- asp.net – IIS 6如何从http://example.com/*重定
- asp.net – 为会话设置文化
- asp.net-mvc – ASP.NET MVC 3区域 – 无法使用自
- asp.net-core-2.0 – 如何从Core 2 RazorPage Vi
- asp.net – 通过Web服务访问连接字符串
- 在.NET应用程序中本地化大量文本的策略
- asp.net-mvc – 使用CORS在WebAPI中将text / pla
- asp.net – 授权web.config中的属性对授权节点
- asp.net-membership – 如果我使用aspnet_member
热点阅读