需要一个完整的示例来处理未处理的异常,使用“ExceptionHandler”在ASP.NET Web Api? [英] Need a complete sample to handle unhandled exceptions using "ExceptionHandler" in ASP.NET Web Api?
问题描述
我已经检查过此链接
http://www.asp.net/web-api/overview/web-api-routing-and-actions/web-api-global-error-handling 。
在这个链接中,他们提到这样
I had checked this link http://www.asp.net/web-api/overview/web-api-routing-and-actions/web-api-global-error-handling. In this link they mentioned like this
class OopsExceptionHandler : ExceptionHandler
{
public override void HandleCore(ExceptionHandlerContext context)
{
context.Result = new TextPlainErrorResult
{
Request = context.ExceptionContext.Request,
Content = "Oops! Sorry! Something went wrong." +
"Please contact support@contoso.com so we can try to fix it."
};
}
private class TextPlainErrorResult : IHttpActionResult
{
public HttpRequestMessage Request { get; set; }
public string Content { get; set; }
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
HttpResponseMessage response =
new HttpResponseMessage(HttpStatusCode.InternalServerError);
response.Content = new StringContent(Content);
response.RequestMessage = Request;
return Task.FromResult(response);
}
}
}
我不知道如何在我的Web API操作中调用此类。所以可以使用这个 ExceptionHandler
给我完整的样本。
I don't know how to call this class in my Web API actions. So can any one give me the complete sample using this ExceptionHandler
.
推荐答案
在您的WebApi配置中,您需要添加以下行:
In your WebApi config your need to add the line:
config.Services.Replace(typeof (IExceptionHandler), new OopsExceptionHandler());
还要确保您已经创建了实现IExceptionHandler的基础ExceptionHandler类:
Also make sure you have created the base ExceptionHandler class that implements IExceptionHandler:
public class ExceptionHandler : IExceptionHandler
{
public virtual Task HandleAsync(ExceptionHandlerContext context,
CancellationToken cancellationToken)
{
if (!ShouldHandle(context))
{
return Task.FromResult(0);
}
return HandleAsyncCore(context, cancellationToken);
}
public virtual Task HandleAsyncCore(ExceptionHandlerContext context,
CancellationToken cancellationToken)
{
HandleCore(context);
return Task.FromResult(0);
}
public virtual void HandleCore(ExceptionHandlerContext context)
{
}
public virtual bool ShouldHandle(ExceptionHandlerContext context)
{
return context.ExceptionContext.IsOutermostCatchBlock;
}
}
请注意,这只会处理不是在其他地方处理(例如通过例外过滤器)。
Note that this will only deal with exceptions that are not handled elsewhere (e.g. by Exception filters).
这篇关于需要一个完整的示例来处理未处理的异常,使用“ExceptionHandler”在ASP.NET Web Api?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!