&的ExceptionHandler

&的ExceptionHandler

本文介绍了需要一个完整的示例使用&QUOT来处理未处理的异常;&的ExceptionHandler QUOT;在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 linkhttp://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 [email protected] 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

推荐答案

在您的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).

这篇关于需要一个完整的示例使用&QUOT来处理未处理的异常;&的ExceptionHandler QUOT;在ASP.NET的Web API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 02:07