Bobcat88
Bobcat88

Reputation: 758

ASP.NET Web API Stack Trace Not Available - UseProblemDetails

It has been a while since I developed an API so bear with me. I have created a new web API in the new .NET 5.0 framework. I have tried using Hellang.Middleware.ProblemDetails nuget for my error handling middleware. Seems to be working, but I cannot get any stack trace details to show for life the me, is there something I am missing?

I can only get the following details:

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

Here is relevant code from my startup 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();
        });
    }

Upvotes: 2

Views: 1396

Answers (2)

George Anasta-Basic
George Anasta-Basic

Reputation: 11

Usually the 404 is the error you get because the API can't find the method, try to be sure for the url.

For example

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

Your url must be like

http://theIpYouChoose/api/AnyNameyouWantForRoute/parameter

If you have a typo in this you will not find the method to call and you will get 404

Upvotes: 0

Adrian
Adrian

Reputation: 473

The returned ProblemDetails is for a 404. This wouldn't have a stack trace associated with it. By the looks of it in production if an exception occurs then you will get a raw 500, whereas in development it should render the stack in the developer exception page. Try introducing an obvious exception and see what is returned.

The following link (though outdated) provides some more details on this: https://andrewlock.net/handling-web-api-exceptions-with-problemdetails-middleware/

Upvotes: 1

Related Questions