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

前端之家收集整理的这篇文章主要介绍了如何通过Asp.net WebAPI中的异常过滤器传递内容?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
考虑以下代码

我的问题是:

1)我似乎无法将错误转发给HttpContent

2)我不能使用CreateContent扩展方法,因为context.Response.Content.CreateContent上不存在

这里的例子似乎只提供StringContent,我希望能够将内容作为JsobObject传递:
http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling

  1. public class ServiceLayerExceptionFilter : ExceptionFilterAttribute
  2. {
  3. public override void OnException(HttpActionExecutedContext context)
  4. {
  5. if (context.Response == null)
  6. {
  7. var exception = context.Exception as ModelValidationException;
  8.  
  9. if ( exception != null )
  10. {
  11. var modelState = new ModelStateDictionary();
  12. modelState.AddModelError(exception.Key,exception.Description);
  13.  
  14. var errors = modelState.SelectMany(x => x.Value.Errors).Select(x => x.ErrorMessage);
  15.  
  16. // Cannot cast errors to HttpContent??
  17. // var resp = new HttpResponseMessage(HttpStatusCode.BadRequest) {Content = errors};
  18. // throw new HttpResponseException(resp);
  19.  
  20. // Cannot create response from extension method??
  21. //context.Response.Content.CreateContent
  22. }
  23. else
  24. {
  25. context.Response = new HttpResponseMessage(context.Exception.ConvertToHttpStatus());
  26. }
  27. }
  28.  
  29. base.OnException(context);
  30. }
  31.  
  32. }

解决方法

  1. context.Response = new HttpResponseMessage(context.Exception.ConvertToHttpStatus());
  2. context.Response.Content = new StringContent("Hello World");

如果要传递复杂对象,还可以使用CreateResponse(在RC中添加以替换不再存在的泛型HttpResponseMessage< T>类)方法

  1. context.Response = context.Request.CreateResponse(
  2. context.Exception.ConvertToHttpStatus(),new Myviewmodel { Foo = "bar" }
  3. );

猜你在找的asp.Net相关文章