aspnetcore: StatusCodePages middleware returns both JSON Problem Details & plaintext content for responses to requests from browsers

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

The StatusCodePagesMiddleware is returning both JSON Problem Details and plain text content (concatenated together) when the request’s Accept header contains certain combinations of media types. This can be easily seen by making a request from a browser (reproduced using Edge latest on Windows).

Expected Behavior

The response should only contain either plain text or JSON Problem Details content, depending on the value of the Accept header.

Steps To Reproduce

  1. Create a new ASP.NET Core Web API application (minimal)
  2. In Program.cs add a call to builder.Services.AddProblemDetails() to enable the IProblemDetailsService
  3. In Program.cs add a call to app.UseStatusCodePages() to add the StatusCodePagesMiddleware to the pipeline
  4. Run the application
  5. Make a request from a browser to “/test” to force a 404 response

Example Program.cs:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddProblemDetails();

var app = builder.Build();

app.UseStatusCodePages();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.MapGet("/", () => new { hello = "World" });

app.Run();

Result: image

Accet header content for request from browser:

text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9

Exceptions (if any)

No response

.NET Version

7.0.200-preview.22605.5

Anything else?

No response

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 20 (18 by maintainers)

Most upvoted comments

Oh, I thought you were referring to a fix for this issue. This issue should still be fixed regardless.

Moving UseStatusCodePages() and UseExceptionHandler() to the top was the first thing I have tried. But it did not work until I updated Visual Studio (I was on the latest minor but not the patch version) and the SDK. Now everything works correctly.

Thanks. Both answers were very helpful.

Is there a way to fix this behavior in .NET 7?

We don’t typically backport bug fixes that include a new API. @DamianEdwards was there a workaround for this other than running the app from the CLI when you ran into it?

  • ValueTask TryWriteAsync(ProblemDetailsContext context, out bool result)

Async APIs can’t have out parameters.

One other alternative: IProblemDetailsService.CanWrite(ProblemDetailsContext ) that mirrors IProblemDetailsWriter