gpt4 book ai didi

c# - 全局异常处理 Web Api 2

转载 作者:行者123 更新时间:2023-11-30 12:21:47 27 4
gpt4 key购买 nike

我正在尝试弄清楚如何在 .NET Web Api 2 中实现全局异常处理程序。

我尝试按照 Microsoft 此处列出的示例进行操作: https://learn.microsoft.com/en-us/aspnet/web-api/overview/error-handling/web-api-global-error-handling

但是当异常发生时,它什么也没做。

这是我的代码:

public class GlobalExceptionHandler : ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
Trace.WriteLine(context.Exception.Message);

context.Result = new TextPlainErrorResult
{
Request = context.ExceptionContext.Request,
Content = "Oops! Sorry! Something went wrong." +
"Please contact support@testme.com so we can try to fix it."
};
}

private class TextPlainErrorResult : IHttpActionResult
{
public HttpRequestMessage Request { private get; set; }

public string Content { private get; set; }

public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response =
new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent(Content),
RequestMessage = Request
};
return Task.FromResult(response);
}
}
}

是否有更好的方法(或更合适的方法)来实现全局异常处理程序?

最佳答案

尝试将其添加到您的 WebApiConfig

webConfiguration.Services.Replace(typeof(IExceptionHandler), new MyExceptionHandler()); // You have to use Replace() because only one handler is supported

webConfiguration.Services.Add(typeof(IExceptionLogger), new MyExceptionLogger()); // webConfiguration is an instance of System.Web.Http.HttpConfiguration

关于c# - 全局异常处理 Web Api 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43952014/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com