gpt4 book ai didi

c# - Asp.net Core UseExceptionHandler 不工作 POST 请求

转载 作者:行者123 更新时间:2023-11-30 23:00:12 29 4
gpt4 key购买 nike

在我的 .Net Core 2.0 应用程序中,我实现了 UseExceptionHandler 来全局处理异常。但重定向仅适用于 GET 方法和 POST 方法总是返回 Status Code: 404;未找到

这是我的 Startup.cs 配置方法

public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
ILoggerFactory loggerFactory)
{
app.UseCors(builder => builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();

if (env.IsDevelopment())
{
app.UseStatusCodePages();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
app.UseDeveloperExceptionPage();
app.UseExceptionHandler("/api/v1/Error");
}
else
{
app.UseExceptionHandler("/api/v1/Error");
}

app.UseMvc();
app.UseSwagger();

app.UseSwaggerUI(c =>
{
c.RoutePrefix = "docs";
c.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 Docs");
c.SwaggerEndpoint("/[]virtualDir]/swagger/v1/swagger.json", "V1 Docs");
});
}

错误 Controller 是

[Route("api/v1/[controller]")]
public class ErrorController : Controller
{
private readonly IErrorLoggerService _errorLoggerService;

public ErrorController(IErrorLoggerService errorLoggerService)
{
_errorLoggerService= errorLoggerService;
}
[HttpGet]
public IActionResult Get()
{
// Get the details of the exception that occurred
var exceptionFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
var errorLog = new ErrorLog();

if (exceptionFeature != null)
{
// Get which route the exception occurred at
var routeWhereExceptionOccurred = exceptionFeature.Path;

// Get the exception that occurred
var exceptionThatOccurred = exceptionFeature.Error;

// TODO: save exception in db
errorLog = new ErrorLog
{
Application = routeWhereExceptionOccurred,
Source = exceptionThatOccurred.Source,
CreatedDate = DateTime.Now,
Host = exceptionThatOccurred.InnerException?.ToString(),
Type = exceptionThatOccurred.Message,
Detail = exceptionThatOccurred.StackTrace
};
_errorLoggerService.Save(errorLog);
return Json(errorLog);
}

return Json(errorLog);
}
}

如何解决?

最佳答案

根据documentation :

In an MVC app, don't decorate the error handler action method with HTTP method attributes, such as HttpGet. Explicit verbs prevent some requests from reaching the method. Allow anonymous access to the method so that unauthenticated users are able to receive the error view.

因此,您的错误可能HttpGet 属性中。不要使用它,而是遵循文档:

[Route("")]
[AllowAnonymous]
public IActionResult Get()
{
....
}

关于c# - Asp.net Core UseExceptionHandler 不工作 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51719195/

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