-
Notifications
You must be signed in to change notification settings - Fork 9.8k
/
ProblemHttpResult.cs
72 lines (59 loc) · 2.67 KB
/
ProblemHttpResult.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Http.HttpResults;
/// <summary>
/// An <see cref="IResult"/> that on execution will write Problem Details
/// HTTP API responses based on <see href="https://tools.ietf.org/html/rfc7807"/>
/// </summary>
public sealed class ProblemHttpResult : IResult, IStatusCodeHttpResult, IContentTypeHttpResult, IValueHttpResult, IValueHttpResult<ProblemDetails>
{
/// <summary>
/// Creates a new <see cref="ProblemHttpResult"/> instance with
/// the provided <paramref name="problemDetails"/>.
/// </summary>
/// <param name="problemDetails">The <see cref="ProblemDetails"/> instance to format in the entity body.</param>
internal ProblemHttpResult(ProblemDetails problemDetails)
{
ProblemDetails = problemDetails;
ProblemDetailsDefaults.Apply(ProblemDetails, statusCode: null);
}
/// <summary>
/// Gets the <see cref="ProblemDetails"/> instance.
/// </summary>
public ProblemDetails ProblemDetails { get; }
object? IValueHttpResult.Value => ProblemDetails;
ProblemDetails? IValueHttpResult<ProblemDetails>.Value => ProblemDetails;
/// <summary>
/// Gets the value for the <c>Content-Type</c> header: <c>application/problem+json</c>
/// </summary>
public string ContentType => "application/problem+json";
/// <summary>
/// Gets the HTTP status code.
/// </summary>
public int StatusCode => ProblemDetails.Status!.Value;
int? IStatusCodeHttpResult.StatusCode => StatusCode;
/// <inheritdoc/>
public async Task ExecuteAsync(HttpContext httpContext)
{
ArgumentNullException.ThrowIfNull(httpContext);
var loggerFactory = httpContext.RequestServices.GetRequiredService<ILoggerFactory>();
var logger = loggerFactory.CreateLogger(typeof(ProblemHttpResult));
var problemDetailsService = httpContext.RequestServices.GetService<IProblemDetailsService>();
if (StatusCode is { } code)
{
HttpResultsHelper.Log.WritingResultAsStatusCode(logger, code);
httpContext.Response.StatusCode = code;
}
if (problemDetailsService is null || !await problemDetailsService.TryWriteAsync(new() { HttpContext = httpContext, ProblemDetails = ProblemDetails }))
{
await HttpResultsHelper.WriteResultAsJsonAsync(
httpContext,
logger,
value: ProblemDetails,
ContentType);
}
}
}