Ani*_*l D 8 c# exception asp.net-core-mvc asp.net-core-2.0
在我的 .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");
});
}
Run Code Online (Sandbox Code Playgroud)
错误控制器是
[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);
}
}
Run Code Online (Sandbox Code Playgroud)
如何修复它?
根据文档:
在 MVC 应用程序中,不要使用 HTTP 方法属性(例如 HttpGet)来修饰错误处理程序操作方法。显式动词会阻止某些请求到达该方法。允许匿名访问该方法,以便未经身份验证的用户能够接收错误视图。
所以,你的错误可能是在HttpGet属性上。不要使用它,而是按照文档进行操作:
[Route("")]
[AllowAnonymous]
public IActionResult Get()
{
....
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5920 次 |
| 最近记录: |