如何通过Asp.net WebAPI中的异常过滤器传递内容?
发布时间:2021-01-11 20:30:29 所属栏目: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" } ); (编辑:4S站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-mvc – 存储库与DAL中的服务模式:EF和Dapper
- asp.net-mvc-3 – 如何将复选框绑定到mvc3中的viewmodel
- asp.net-mvc – 在ASP.NET MVC中的LinkButton
- asp.net下使用jquery 的ajax+WebService+json 实现无刷新取
- asp.net – [DataType(DataType.EmailAddress)]和[EmailAdd
- asp.net-mvc-3 – “字段宽度必须是数字.”在客户端
- 如何在ASP.NET中的GridView中定义CellPadding
- asp.net-mvc – 当我不知道内容类型时如何返回文件结果
- asp.net – Mocking HttpContext不起作用
- 在mvc4 asp.net中的Razor View中的模型声明