![](/img/trans.png)
[英]ASP.NET Core error handler without HTTP verb throws Swashbuckle exception
[英]Pass an exception to the default ASP.Net CORE error handler
我在 VS Community 2019 的新版本中使用 ASP.NET CORE 3.1 項目
在我的startup.cs
文件的Configure(IApplicationBuilder app, IWebHostEnvironment env)
中,我有以下行:
app.UseExceptionHandler("/Home/Error");
因此,當我在Controller
的某處拋出錯誤時,例如
throw new Exception("User Not Found!");
然后這會反彈到HomeController
中的默認IActionResult
:
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
我希望將某些東西( Exception
或其消息)傳遞給IActionResult Error()
但我不確定這是否可能。
於是我想
BaseController 中拋出的Exception
是否可以從Error IActionResult
BaseController
? 可能通過使用HttpContext
或Activity
?
我似乎無法使用智能感知找到任何東西,不確定我是否以正確的方式接近它,並且可能需要設置一個全新的錯誤處理系統。
也許你應該添加 ErrorHandlingMiddleware
app.UseMiddleware<ErrorHandlingMiddleware>();
public class ErrorHandlingMiddleware
{
private readonly RequestDelegate next;
private readonly ILogger _logger;
public ErrorHandlingMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
{
this.next = next;
_logger = loggerFactory.CreateLogger<ErrorHandlingMiddleware>();
}
public async Task Invoke(HttpContext context /* other dependencies */)
{
try
{
await next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception ex)
{
var code = HttpStatusCode.InternalServerError; // 500 if unexpected
if (ex is AuthenticationException)
{
code = HttpStatusCode.Unauthorized;
}
var result = JsonConvert.SerializeObject(new
{
Status = "Error",
ErrorCode = (int)code,
ErrorMessage = ex.Message,
});
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)code;
return context.Response.WriteAsync(result);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.