我在我的mvc具有全球ExceptionFilter返回例外\的WebAPI申請註冊爲:如何優雅地從的WebAPI消息處理程序
public virtual void RegisterHttpFilters(HttpConfiguration config)
{
config.Filters.Add(new MyExceptionFilter(_exceptionHandler));
}
其中MyExceptionFilter是:
public class MyExceptionFilter : ExceptionFilterAttribute
{
private readonly IMyExceptionHandler m_exceptionHandler;
public MyExceptionFilter(IMyExceptionHandler exceptionHandler)
{
m_exceptionHandler = exceptionHandler;
}
public override void OnException(HttpActionExecutedContext context)
{
Exception ex = context.Exception;
if (ex != null)
{
object response = null;
HttpStatusCode statusCode = m_exceptionHandler != null
? m_exceptionHandler.HandleException(ex, out response)
: HttpStatusCode.InternalServerError;
context.Response = context.Request.CreateResponse(statusCode, response ?? ex);
}
base.OnException(context);
}
}
該過濾器返回的所有異常作爲json對象,並允許一些IMyExceptionHandler實現來定製返回的對象。
這一切都很好。直到我有我的一些消息處理程序的異常:
public class FooMessageHandler : DelegatingHandler
{
private readonly Func<IBar> _barFactory;
public FooMessageHandler(Func<IBar> barFactory)
{
_barFactory = varFactory;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
request.Properties["MY_BAR"] = _barFactory();
return base.SendAsync(request, cancellationToken);
}
}
正如你可以看到這個處理程序創建的一些組件,並把它放到當前的HTTP請求消息。 當FuncOfIBar發生異常時,我會得到死亡黃色屏幕。我的ExceptionFilter沒有被調用。
我想專門捕獲在消息處理異常,並返回HttpResponseException,但它不會改變任何東西 - 仍然得到YSOD:
public class XApplicationInitializerMessageHandler : DelegatingHandler
{
private readonly Func<IXCoreApplication> _appFactory;
private readonly IXExceptionHandler m_exceptionHandler;
public XApplicationInitializerMessageHandler(Func<IXCoreApplication> appFactory, IXExceptionHandler exceptionHandler)
{
ArgumentValidator.EnsureArgumentNotNull(appFactory, "appFactory");
_appFactory = appFactory;
m_exceptionHandler = exceptionHandler;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
try
{
request.SetApplication(_appFactory());
}
catch (Exception ex)
{
object resultObject = null;
HttpStatusCode statusCode = m_exceptionHandler != null
? m_exceptionHandler.HandleException(ex, out resultObject)
: HttpStatusCode.InternalServerError;
HttpResponseMessage responseMessage = request.CreateResponse(statusCode, resultObject ?? ex);
throw new HttpResponseException(responseMessage);
}
return base.SendAsync(request, cancellationToken);
}
}
}
我想我的應用程序的行爲是無論發生什麼異常:在ApiController或消息處理程序中。
如何做到這一點?
我知道Application_Error,但我想保持HttpApplication定製不可觸摸。
http://stackoverflow.com /問題/ 13013973/ASP網的Web-API的默認錯誤信息 – Timeless 2015-11-18 16:19:11