首页 > 解决方案 > 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?}");
    });
}

标签: asp.net-core

解决方案


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

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/


推荐阅读