Skip to content
This repository has been archived by the owner on Dec 14, 2018. It is now read-only.

Set ProblemDetails status field during ObjectResult formatting #8118

Merged
merged 1 commit into from
Jul 20, 2018
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
5 changes: 5 additions & 0 deletions src/Microsoft.AspNetCore.Mvc.Core/ObjectResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ public virtual void OnFormatting(ActionContext context)
if (StatusCode.HasValue)
{
context.HttpContext.Response.StatusCode = StatusCode.Value;

if (Value is ProblemDetails details && !details.Status.HasValue)
{
details.Status = StatusCode.Value;
}
}
}
}
Expand Down
33 changes: 33 additions & 0 deletions test/Microsoft.AspNetCore.Mvc.Core.Test/ObjectResultTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
Expand Down Expand Up @@ -61,6 +62,38 @@ public async Task ObjectResult_ExecuteResultAsync_SetsStatusCode()
Assert.Equal(404, actionContext.HttpContext.Response.StatusCode);
}

[Fact]
public async Task ObjectResult_ExecuteResultAsync_SetsProblemDetailsStatus()
{
// Arrange
var modelState = new ModelStateDictionary();

var details = new ValidationProblemDetails(modelState);

var result = new ObjectResult(details)
{
StatusCode = StatusCodes.Status422UnprocessableEntity,
Formatters = new FormatterCollection<IOutputFormatter>()
{
new NoOpOutputFormatter(),
},
};

var actionContext = new ActionContext()
{
HttpContext = new DefaultHttpContext()
{
RequestServices = CreateServices(),
}
};

// Act
await result.ExecuteResultAsync(actionContext);

// Assert
Assert.Equal(StatusCodes.Status422UnprocessableEntity, details.Status.Value);
}

private static IServiceProvider CreateServices()
{
var services = new ServiceCollection();
Expand Down