dotnet / dotnet/aspnetcore

Make it clear what accept header supported when using IProblemDetailsService

Open
#56,259 3 comments 0 reactions 0 assignees View on GitHub
area-mvc
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Is your feature request related to a problem? Please describe the problem.

If the current request's accept header is not application/json (I don't know the full supported list), this exception is raised:
> "Unable to find a registered `IProblemDetailsWriter` that can write to the given context."

I was working on a new controller without adding any of the metadata and attributes, and I wanted to use the new exception handler introduced in .NET 8 with `IProblemDetailsService`, I spent a few hours searching for why my custom exception handler was not working when it comes to the call to `WriteAsync` of `IProblemDetailsService`, which threw the previous exception.
I disabled "Just my code" in Visual Studio, and found it fails in this method:
```
public bool CanWrite(ProblemDetailsContext context)
{
IList list = context.HttpContext.Request.Headers.Accept.GetList();
if (list.Count == 0)
{
return true;
}
for (int i = 0; i < list.Count; i++)
{
MediaTypeHeaderValue val = list[i];
if (_jsonMediaType.IsSubsetOf(val) || _problemDetailsJsonMediaType.IsSubsetOf(val))
{
return true;
}
}
return false;
}
```
it returns false, as the accept header of the request was `text/plain`. When I added this attribute to the action, it worked:
```
[Produces(MediaTypeNames.Application.Json)]
```

The exception message is not very helpful... so, if the message can specify why it failed, that would be very helpful and save some time.
Thanks

### Describe the solution you'd like

A clearer exception message, that doesn't assume the developer intentionally used an unsupported accept header and didn't provide their `IProblemDetailsService` implementation.

### Additional context

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.