【问题标题】:Error logging and handling in asp.net core mvcasp.net core mvc 中的错误记录和处理
【发布时间】:2021-03-31 04:38:25
【问题描述】:

假设您在代码中犯了一个错误(例如 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?}");
    });
}

【问题讨论】:

  • 您的代码在哪里?此错误很简单,但需要特定代码来帮助诊断问题。
  • @Hopeless 您的意思是 UseExceptionHandler 应该适用于此类错误吗?我认为它应该在其他地方被抓住
  • 不,我的意思是修复错误,但看起来你想记录它,没关系
  • 如果您正确配置了日志记录,则应该可以很好地记录此错误。因此,如果您发布配置代码会很有帮助。其他错误呢?他们是否正确记录?至少在调试时,我已经多次看到这个错误被记录在输出(调试)窗口中,就像其他类型的错误一样。
  • 我放了代码。我在输出调试中看不到任何东西。我能够在代码 UseStatusCodePages lambda 中捕获它的唯一方法。我可以在那里添加日志记录。但是感觉不太对劲,除了415错误码我也没找到更多信息。

标签: asp.net-core


【解决方案1】:

尝试使用中间件。为中间件创建新类:

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中配置这个类:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory fac)

{

...
app.UseMiddleware<ErrorLoggingMiddleware>();
...

}

请在以下位置找到更多详细信息: https://blog.elmah.io/error-logging-middleware-in-aspnetcore/

【讨论】:

    猜你喜欢
    • 2011-06-03
    • 2022-01-07
    • 1970-01-01
    • 2010-11-05
    • 2014-03-05
    • 1970-01-01
    • 2016-07-29
    • 2020-10-31
    • 1970-01-01
    相关资源
    最近更新 更多