在我的WebApi代碼中,我引發了一個HttpResponseException,它使請求管道短路並生成有效的Http響應。但是,我試圖將webApi與elmah日誌集成,但HttpResponseExeptions沒有顯示出來。Elmah不會使用WebAPI和HttpResponseException記錄異常
我有web.config中建立了ELMAH並具有以下代碼:
在Global.asx.cs:
static void ConfigureWebApi(HttpConfiguration config)
{
config.Filters.Add(new ServiceLayerExceptionFilter());
config.Filters.Add(new ElmahHandledErrorLoggerFilter());
config.DependencyResolver = new WebApiDependencyResolver(ObjectFactory.Container);
}
篩選:
public class ElmahHandledErrorLoggerFilter : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
base.OnException(actionExecutedContext);
ErrorSignal.FromCurrentContext().Raise(actionExecutedContext.Exception);
}
}
發生異常的代碼:
public Task<FileUpModel> UploadFile()
{
if (Request.Content.IsMimeMultipartContent())
{
var provider = new TolMobileFormDataStreamProvider("C:\images\");
var task = Request.Content.ReadAsMultipartAsync(provider).ContinueWith(
t =>
{
if (t.IsFaulted || t.IsCanceled)
throw new HttpResponseException(HttpStatusCode.InternalServerError);
var fileInfo = provider.FileData.FirstOrDefault();
if (fileInfo == null)
// the exception here isn't logged by Elmah?!
throw new HttpResponseException(HttpStatusCode.InternalServerError);
var uploadModel = new FileUpModel { success = true };
return uploadModel;
});
return task;
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
}
}
誰能實施這個之前讓我知道我做錯了什麼嗎?
那麼我如何才能使它工作? – jaffa
你不能。從動作拋出時,只會爲非HttpResponseExceptions調用過濾器。 –
當我創建HttpResponseException時,我使用手動Elmah錯誤信號,這似乎工作正常。 – jaffa