在我的.Net Core 2.0应用程序中,我实现了 UseExceptionHandler 来全局处理异常。但是重定向仅适用于GET方法,而POST方法始终返回状态代码: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");
});
}
错误控制器是
[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);
}
}
如何解决?
答案 0 :(得分:1)
在MVC应用程序中,请勿使用HTTP方法属性(例如HttpGet)来修饰错误处理程序操作方法。显式动词阻止某些请求到达该方法。允许匿名访问该方法,以便未经身份验证的用户可以接收错误视图。
因此,您的错误可能是HttpGet
属性中的 。不要使用它,而是按照文档进行操作:
[Route("")]
[AllowAnonymous]
public IActionResult Get()
{
....
}
答案 1 :(得分:0)
您应该能够从Error方法中删除[HttpGet]
,因为它是造成不必要限制的原因。
//[HttpGet]
public IActionResult Get()
{
....
}