1+ namespace Microsoft . AspNetCore . Mvc . Versioning
2+ {
3+ using Microsoft . AspNetCore . Mvc . Infrastructure ;
4+ using Microsoft . Extensions . DependencyInjection ;
5+ using System ;
6+
7+ /// <summary>
8+ /// Represents the provider for creating HTTP error responses matching <see cref="ProblemDetails"/> and RFC 7807.
9+ /// </summary>
10+ [ CLSCompliant ( false ) ]
11+ public class ProblemDetailsErrorResponseProvider : IErrorResponseProvider
12+ {
13+ /// <inheritdoc />
14+ public virtual IActionResult CreateResponse ( ErrorResponseContext context )
15+ {
16+ if ( context == null )
17+ {
18+ throw new ArgumentNullException ( nameof ( context ) ) ;
19+ }
20+
21+ return NewResult ( context ) ;
22+ }
23+
24+ /// <summary>
25+ /// Creates and returns new problem details.
26+ /// </summary>
27+ /// <param name="context">The <see cref="ErrorResponseContext">error context</see> used to generate response.</param>
28+ /// <returns>New <see cref="ProblemDetails">problem details</see>.</returns>
29+ protected virtual ProblemDetails NewProblemDetails ( ErrorResponseContext context )
30+ {
31+ if ( context == null )
32+ {
33+ throw new ArgumentNullException ( nameof ( context ) ) ;
34+ }
35+
36+ var httpContext = context . Request . HttpContext ;
37+ var factory = httpContext . RequestServices . GetRequiredService < ProblemDetailsFactory > ( ) ;
38+
39+ return factory . CreateProblemDetails ( httpContext , context . StatusCode , context . ErrorCode , default , context . Message , default ) ;
40+ }
41+
42+ /// <summary>
43+ /// Creates and returns a new result.
44+ /// </summary>
45+ /// <param name="context">The <see cref="ErrorResponseContext">error context</see> used to generate response.</param>
46+ /// <returns>A new <see cref="ObjectResult"/>.</returns>
47+ protected virtual ObjectResult NewResult ( ErrorResponseContext context )
48+ {
49+ if ( context == null )
50+ {
51+ throw new ArgumentNullException ( nameof ( context ) ) ;
52+ }
53+
54+ // match behavior of IClientErrorFactory.GetClientError
55+ // REF: https://github.com/dotnet/aspnetcore/blob/master/src/Mvc/Mvc.Core/src/Infrastructure/ProblemDetailsClientErrorFactory.cs#L17
56+ return new ObjectResult ( NewProblemDetails ( context ) )
57+ {
58+ StatusCode = context . StatusCode ,
59+ ContentTypes =
60+ {
61+ "application/problem+json" ,
62+ "application/problem+xml" ,
63+ } ,
64+ } ;
65+ }
66+ }
67+ }
0 commit comments