jaf*_*ffa 6 asp.net asp.net-web-api
考虑以下代码:
我的问题是:
1)我似乎无法将错误转发给HttpContent
2)我不能使用CreateContent扩展方法,因为context.Response.Content.CreateContent上不存在
这里的例子似乎只提供了StringContent,我希望能够将内容作为JsobObject传递:http: //www.asp.net/web-api/overview/web-api-routing-and-actions/异常处理
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);
}
}
Run Code Online (Sandbox Code Playgroud)
Dar*_*rov 13
context.Response = new HttpResponseMessage(context.Exception.ConvertToHttpStatus());
context.Response.Content = new StringContent("Hello World");
Run Code Online (Sandbox Code Playgroud)
如果要传递复杂对象,还可以使用CreateResponse(在RC中添加以替换HttpResponseMessage<T>不再存在的泛型类)方法:
context.Response = context.Request.CreateResponse(
context.Exception.ConvertToHttpStatus(),
new MyViewModel { Foo = "bar" }
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5240 次 |
| 最近记录: |