考虑以下代码:
我的问题是:
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)我似乎无法将错误转换为HttpContent。
2)我无法使用CreateContent扩展方法,因为它不存在于context.Response.Content.CreateContent上。
此处的示例似乎仅提供StringContent,我希望能够将内容传递为JsobObject: http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling。
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);
}
}