【问题标题】:ASP.NET Web API Stack Trace Not Available - UseProblemDetailsASP.NET Web API 堆栈跟踪不可用 - UseProblemDetails
【发布时间】:2021-03-23 07:40:11
【问题描述】:

我已经有一段时间没有开发 API 了,所以请耐心等待。我在新的 .NET 5.0 框架中创建了一个新的 Web API。我尝试使用 Hellang.Middleware.ProblemDetails nuget 来处理我的错误处理中间件。似乎正在工作,但我无法获得任何堆栈跟踪详细信息来终生显示我,我是否缺少某些东西?

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

{"type":"https://httpstatuses.com/404","title":"不是 找到","状态":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();
        });
    }

【问题讨论】:

  • 您能否提供一些有关您尝试发出的请求以及您的控制器和路由代码的信息?不会有任何带有 404 的异常消息,因为它只是一个标准响应类型。如果您想测试获取堆栈跟踪详细信息,请尝试在控制器代码中故意抛出异常并查看响应中发送的内容。

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


【解决方案1】:

通常404是你得到的错误,因为API找不到方法,尝试确定url。

例如

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

你的网址必须是这样的

http://theIpYouChoose/api/AnyNameyouWantForRoute/parameter

如果你有错别字,你将找不到调用的方法,你会得到 404

【讨论】:

  • 试着提供一个例子或方法让你的答案更清楚:)
  • 感谢您的建议,我会在几分钟内编辑我的帖子
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2018-09-18
    • 1970-01-01
    • 2015-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-28
    • 1970-01-01
    相关资源
    最近更新 更多