相关疑难解决方法(0)

WebApi v2 ExceptionHandler未调用

为什么ExceptionHandler永远不会调用自定义,而是返回标准响应(不是我想要的)?

像这样注册

config.Services.Add(typeof(IExceptionLogger), new ElmahExceptionLogger());
config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());
Run Code Online (Sandbox Code Playgroud)

并实现这样的

public class GlobalExceptionHandler : ExceptionHandler
{
    public override void Handle(ExceptionHandlerContext context)
    {
        context.Result = new ExceptionResponse
        {
            statusCode = context.Exception is SecurityException ? HttpStatusCode.Unauthorized : HttpStatusCode.InternalServerError,
            message = "An internal exception occurred. We'll take care of it.",
            request = context.Request
        };
    }
}

public class ExceptionResponse : IHttpActionResult
{
    public HttpStatusCode statusCode { get; set; }
    public string message { get; set; }
    public HttpRequestMessage request { get; set; …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-web-api

23
推荐指数
2
解决办法
1万
查看次数

标签 统计

asp.net-web-api ×1

c# ×1