如何通过Asp.net WebAPI中的异常过滤器传递内容?
发布时间:2021-01-12 03:38:10 所属栏目: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菜单项
- asp.net-mvc – System.Web.Mvc.WebViewPage.Model.get返回
- asp.net 删除项目文件/文件夹IIS重启,Session丢失问题
- 在asp.net中使用加密数据库联接字符串保证数据安全
- ASP.Net Web应用程序安全性不适用于IIS 7?
- asp.net-web-api – 在WebApi OData中为OData服务文档基URL
- 下载期间的ASP.net内存使用情况
- 序列化 – Newtonsoft中的TypeNameHandling需要$type作为第
- 一个简答的Access下的分页asp.net代码
- asp.net-core – ASP.Net 5类库中的EntityFramework命令?