asp.net-core - asp.net core mvc 中的错误记录和处理
问题描述
假设您在代码中犯了一个错误(例如415 Unsupported Media Type asp.net core)。并从 Web 请求中获取 415 错误。我们如何找到有关错误的更多信息?我们如何记录它?
似乎.UseExceptionHandler()
In Startup.cs 没有抓住它。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
// app.UseExceptionHandler("/Home/Error");
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseStatusCodePages(async context =>
{
context.HttpContext.Response.ContentType = "text/plain";
var statusCodeData = context.HttpContext.Features.Get<IStatusCodePagesFeature>();
await context.HttpContext.Response.WriteAsync(
"Status code page, status code: " +
context.HttpContext.Response.StatusCode);
});
// app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
解决方案
尝试使用中间件。为中间件创建新类:
public class ErrorLoggingMiddleware
{
private readonly RequestDelegate _next;
public ErrorLoggingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception exception)
{
// Handle exception
await HandleExceptionAsync(context, exception, HttpStatusCode.InternalServerError);
}
}
private Task HandleExceptionAsync(HttpContext context, Exception exception, HttpStatusCode statusCode)
{
context.Response.StatusCode = (int)statusCode;
// TO DO: Log exceptions : Azure AppInsights or File
var message = "The requested resource was not found";
var response = new
{
ErrorDescription = $"{(int)statusCode} - {message}",
ErrorCode = message
};
string responseStringContent;
context.Response.ContentType = Application.Json;
responseStringContent =
JsonSerializer.Serialize(response, new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase });
return context.Response.WriteAsync(responseStringContent);
}
}
然后在Startup中配置这个类:
公共无效配置(IApplicationBuilder 应用程序,IHostingEnvironment env,ILoggerFactory fac)
{
...
app.UseMiddleware<ErrorLoggingMiddleware>();
...
}
请在以下位置找到更多详细信息: https ://blog.elmah.io/error-logging-middleware-in-aspnetcore/
推荐阅读
- javascript - youtube api 的异步调用导致 player.getDuration is not a function 错误
- c - 服务器无法从客户端正确读取数据 || c语言
- ibm-watson - 提供的 API 密钥找不到
- c# - 返回值和 bool
- c - 如何将内存分配给一个空字符串数组
- http - Sony API - 简单的 http post 格式
- excel - VBA - 将非空单元格值整理到新列
- reactjs - 在 React 中将 className 添加到数组的第一个 div
- c++ - 为什么它不输出响应?
- arduino - 如何将数据写入文本文件然后发送到 Arduino ESP32 上的 FTP 服务器