ASP.NET Web API 堆栈跟踪不可用 - UseProblemDetails

ASP.NET Web API Stack Trace Not Available - UseProblemDetails

我开发 API 已经有一段时间了,请耐心等待。我在新的 .NET 5.0 框架中创建了一个新的网站 API。我尝试使用 Hellang.Middleware.ProblemDetails nuget 作为我的错误处理中间件。似乎在工作,但我无法获得任何堆栈跟踪详细信息来显示我的生活,我是否遗漏了什么?

我只能得到以下详细信息:

{"type":"https://httpstatuses.com/404","title":"Not Found","status":404,"traceId":"00-02c4e89a990c5745bc4250cfad83d5e3-bb8c1dab98b44a44-00"}

这是我启动时的相关代码 class:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<CoreDbContext>(op => op.UseSqlServer(AppSettings.DBConnectionString).UseLazyLoadingProxies());
        services.AddControllers().AddNewtonsoftJson(options =>
            options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
        );

        services.AddProblemDetails(opts =>
        {
            // Control when an exception is included
            opts.IncludeExceptionDetails = (ctx, ex) =>
            {
                // Fetch services from HttpContext.RequestServices
                var env = ctx.RequestServices.GetRequiredService<IHostEnvironment>();
                return env.IsDevelopment();
            };
        });
    }

    
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();            
        }

        app.UseProblemDetails();

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }

返回的 ProblemDetails 是针对 404 的。这不会有与之关联的堆栈跟踪。从生产中的外观来看,如果发生异常,您将获得原始 500,而在开发中,它应该在开发人员异常页面中呈现堆栈。尝试引入一个明显的异常并查看返回的内容。

以下 link(虽然已过时)提供了更多详细信息:https://andrewlock.net/handling-web-api-exceptions-with-problemdetails-middleware/

通常 404 是您收到的错误,因为 API 找不到方法,请尝试确定 url.

例如

[HttpGet]  
[Route("api/AnyNameyouWantForRoute/parameter")]  
// your method in controller

你的url一定是

http://theIpYouChoose/api/AnyNameyouWantForRoute/parameter

如果您在此输入错误,您将找不到要调用的方法,您将收到 404