c# - ASP.NET Web API堆栈跟踪不可用-使用ProblemDetails

标签 c# .net error-handling .net-5

自从我开发API以来已经有一段时间了,请多多包涵。我已经在新的.NET 5.0框架中创建了一个新的Web API。我已经尝试将Hellang.Middleware.ProblemDetails nuget用于我的错误处理中间件。似乎可以正常工作,但是我无法获得任何堆栈跟踪详细信息来终生显示我,我是否缺少某些东西?
我只能得到以下详细信息:

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


这是我的启动类中的相关代码:
    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,而在开发中,它将在开发人员异常页面中呈现堆栈。尝试引入一个明显的异常,看看返回了什么。
以下链接(尽管已过时)对此提供了更多详细信息:https://andrewlock.net/handling-web-api-exceptions-with-problemdetails-middleware/

关于c# - ASP.NET Web API堆栈跟踪不可用-使用ProblemDetails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65258981/

相关文章:

c# - 动态模拟远程用户 - c# 和 asp.net

c# - 窗体上的 Mouseenter 和 Mouseleave

javascript - 在对象内调用对象方法——错误: cannot read property of undefined

c# - .net 核心中的库配置?

c# - 使用 C# 和 ASP.Net 设置类型为 ="password"的输入标签的值

c# - 将 SignalR 与 ASP.NET MVC3 结合使用

asp.net - 登录不正确时显示消息

c# - 为什么实例化 Azure 移动服务时出错?

.Net 和插件架构

jquery - 我应该如何处理插件中丢失的图像?