Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/Http/Http.Results/src/HttpResultsHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// The .NET Foundation licenses this file to you under the MIT license.

using System.Diagnostics.CodeAnalysis;
using System.Net.Mime;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
Expand Down Expand Up @@ -34,6 +35,11 @@ public static Task WriteResultAsJsonAsync<TValue>(
return Task.CompletedTask;
}

if (value is ProblemDetails)
{
contentType = MediaTypeNames.Application.ProblemJson;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this only be done when contentType is null?

}

jsonSerializerOptions ??= ResolveJsonOptions(httpContext).SerializerOptions;
var jsonTypeInfo = (JsonTypeInfo<TValue>)jsonSerializerOptions.GetTypeInfo(typeof(TValue));

Expand Down
30 changes: 30 additions & 0 deletions src/Http/Http.Results/test/HttpResultsHelperTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Http.Json;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
Expand Down Expand Up @@ -218,6 +219,35 @@ public async Task WriteResultAsJsonAsync_Works_UsingUnspeakableType(bool useJson
Assert.Equal("ThreeChild", three.Child);
}

[Fact]
public async Task WriteResultAsJsonAsync_SetsProblemJsonContentType_ForProblemDetails()
{
const string Detail = "Explanation of something went wrong :'(";

// Arrange
var value = new ProblemDetails()
{
Detail = Detail,
};
var responseBodyStream = new MemoryStream();
var httpContext = CreateHttpContext(responseBodyStream);
var serializerOptions = new JsonOptions().SerializerOptions;

_ = new NotFound<ProblemDetails>(value);

// Act
await HttpResultsHelper.WriteResultAsJsonAsync(httpContext, NullLogger.Instance, value, jsonSerializerOptions: serializerOptions);

// Assert
var body = JsonSerializer.Deserialize<ProblemDetails>(responseBodyStream.ToArray(), serializerOptions);

Assert.NotNull(body);
Assert.Equal(Detail, body.Detail);
Assert.Equal(StatusCodes.Status404NotFound, body.Status);
Assert.Equal("https://tools.ietf.org/html/rfc9110#section-15.5.5", body.Type);
Assert.Equal("Not Found", body.Title);
}

private static async IAsyncEnumerable<JsonTodo> GetTodosAsync()
{
yield return new JsonTodo() { Id = 1, IsComplete = true, Name = "One" };
Expand Down
24 changes: 17 additions & 7 deletions src/Mvc/Mvc.Core/src/Infrastructure/ObjectResultExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System.Diagnostics;
using System.Globalization;
using System.Net.Mime;
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Formatters;
Expand Down Expand Up @@ -123,18 +124,27 @@ private static void InferContentTypes(ActionContext context, ObjectResult result
{
Debug.Assert(result.ContentTypes != null);

var wasEmpty = result.ContentTypes.Count == 0;

// When dealing with ProblemDetails, we always add ProblemJson and ProblemXml at the
// beginning of the list so that they are preferred over anything else.
if (result.Value is ProblemDetails)
{
Comment thread
Youssef1313 marked this conversation as resolved.
result.ContentTypes.Insert(0, MediaTypeNames.Application.ProblemJson);
result.ContentTypes.Insert(1, MediaTypeNames.Application.ProblemXml);
}

// If the user sets the content type both on the ObjectResult (example: by Produces) and Response object,
// then the one set on ObjectResult takes precedence over the Response object
var responseContentType = context.HttpContext.Response.ContentType;
if (result.ContentTypes.Count == 0 && !string.IsNullOrEmpty(responseContentType))
// then the one set on ObjectResult takes precedence over the Response object.
if (!wasEmpty)
{
result.ContentTypes.Add(responseContentType);
return;
}
Comment thread
Youssef1313 marked this conversation as resolved.

if (result.Value is ProblemDetails)
var responseContentType = context.HttpContext.Response.ContentType;
if (!string.IsNullOrEmpty(responseContentType))
{
result.ContentTypes.Add("application/problem+json");
result.ContentTypes.Add("application/problem+xml");
result.ContentTypes.Add(responseContentType);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -204,8 +204,11 @@ public async Task ExecuteAsync_ForProblemDetailsValue_UsesProblemDetailsJsonCont
MediaTypeAssert.Equal("application/problem+json; charset=utf-8", httpContext.Response.ContentType);
}

[Fact]
public async Task ExecuteAsync_ForProblemDetailsValue_UsesProblemDetailsXMLContentType_BasedOnAcceptHeader()
[Theory]
[InlineData("text/plain")]
[InlineData("application/xml")]
[InlineData("application/json")]
public async Task ExecuteAsync_ForProblemDetailsValue_UsesProblemDetailsXMLContentType_BasedOnAcceptHeader(string resultContentTypes)
{
// Arrange
var executor = CreateExecutor();
Expand All @@ -216,7 +219,7 @@ public async Task ExecuteAsync_ForProblemDetailsValue_UsesProblemDetailsXMLConte

var result = new ObjectResult(new ProblemDetails())
{
ContentTypes = { "text/plain" }, // This will not be used
ContentTypes = { resultContentTypes }, // This will not be used
};
Comment thread
Youssef1313 marked this conversation as resolved.
result.Formatters.Add(new TestJsonOutputFormatter());
result.Formatters.Add(new TestXmlOutputFormatter()); // This will be chosen based on the Accept Headers "application/xml"
Expand All @@ -229,6 +232,27 @@ public async Task ExecuteAsync_ForProblemDetailsValue_UsesProblemDetailsXMLConte
MediaTypeAssert.Equal("application/problem+xml; charset=utf-8", httpContext.Response.ContentType);
}

[Fact]
public async Task ExecuteAsync_ForProblemDetailsValue_UsesPlainTextContentType_WhenNoJsonOrXmlFormattersAreAvailable()
{
// Arrange
var executor = CreateExecutor();

var httpContext = new DefaultHttpContext();
var actionContext = new ActionContext() { HttpContext = httpContext };
httpContext.Request.Headers.Accept = "text/plain";
httpContext.Response.ContentType = "text/plain";

var result = new ObjectResult(new ProblemDetails());
result.Formatters.Add(new TestStringOutputFormatter());

// Act
await executor.ExecuteAsync(actionContext, result);

// Assert
MediaTypeAssert.Equal("text/plain; charset=utf-8", httpContext.Response.ContentType);
}

[Fact]
public async Task ExecuteAsync_NoContentTypeProvidedForProblemDetails_UsesDefaultContentTypes()
{
Expand Down
Loading