Skip to content
Open
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
22 changes: 22 additions & 0 deletions src/Http/Http.Extensions/src/RequestDelegateFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1422,6 +1422,28 @@ private static Expression AddResponseWritingToMethodCall(Expression methodCall,
{
Log.InvalidJsonRequestBody(httpContext, parameterTypeName, parameterName, ex, throwOnBadRequest);
httpContext.Response.StatusCode = StatusCodes.Status400BadRequest;

var problemDetailsService = httpContext.RequestServices.GetService<IProblemDetailsService>();
if (problemDetailsService is not null)
{
IEnumerable<KeyValuePair<string, string[]>> errors =
[
new KeyValuePair<string, string[]>(ex.Path ?? string.Empty, [ex.Message]),
];

var problemDetailsContext = new ProblemDetailsContext()
{
HttpContext = httpContext,
Exception = ex,
ProblemDetails = new HttpValidationProblemDetails(errors)
{
Status = StatusCodes.Status400BadRequest,
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

While looking around, I noticed we don't set the Status on the problem details in the validation filter
https://source.dot.net/#Microsoft.AspNetCore.Routing/[ValidationEndpointFilterFactory.cs](https://source.dot.net/#Microsoft.AspNetCore.Routing/ValidationEndpointFilterFactory.cs,99),99
Should probably do that, either here or a separate change.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Hmm, looks like this will eventually get applied anyways when it reaches to:

ProblemDetailsDefaults.Apply(context.ProblemDetails, httpContext.Response.StatusCode);

problemDetails.Status = statusCode;

This is assuming that the DefaultProblemDetailsWriter is used and not any other custom writer that's written and registered by the user. For the case of a custom implementation, I'm not sure yet, I'll try to come up with a test to demonstrate how the behavior can be different. I assume we will need to also have some consistency there between what MVC does and what minimal API does.

Thanks for pointing that out @BrennanConroy!

},
};

_ = await problemDetailsService.TryWriteAsync(problemDetailsContext);
}

return (null, false);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -291,4 +291,16 @@ public async Task FileUpload_Fails_WithoutAntiforgeryToken()
// Assert
await response.AssertStatusCodeAsync(HttpStatusCode.BadRequest);
}

[Theory]
[InlineData("/post-required-minimal")]
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

We should keep RDF tests in the RDF area https://github.com/dotnet/aspnetcore/tree/main/src/Http/Http.Extensions/test

Should also check that RDG behavior matches probably would put the test in
https://github.com/dotnet/aspnetcore/blob/main/src/Http/Http.Extensions/test/RequestDelegateGenerator/RequestDelegateCreationTests.JsonBody.cs
so it tests both RDF and RDG

[InlineData("/post-required-mvc")]
public async Task PostWithRequiredProperty(string endpoint)
{
var response = await Client.PostAsJsonAsync(endpoint, new { });
var responseString = await response.Content.ReadAsStringAsync();
Assert.Matches("""
{"type":"https://tools.ietf.org/html/rfc9110#section-15.5.1","title":"One or more validation errors occurred\.","status":400,"errors":{"\$":\["JSON deserialization for type 'ModelWithRequiredProperty' was missing required properties including: 'prop'\."]},"traceId":".+?"}
""", responseString);
Comment thread
Youssef1313 marked this conversation as resolved.
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;

using static Microsoft.AspNetCore.Http.Results;
Expand All @@ -9,6 +10,7 @@

builder.Services.AddControllers();
builder.Services.AddAntiforgery();
builder.Services.AddProblemDetails();

var app = builder.Build();

Expand Down Expand Up @@ -53,6 +55,8 @@
return uploadStream.Length;
});

app.MapPost("/post-required-minimal", string (ModelWithRequiredProperty model) => $"Hello {model.Prop}");
Comment thread
Youssef1313 marked this conversation as resolved.

app.Run();

record Person(string Name, int Age);
Expand All @@ -63,6 +67,19 @@ public class MyController : ControllerBase
public string Greet() => $"Hello human";
}

[ApiController]
public class MyApiController
{
[HttpPost("/post-required-mvc")]
public string PostModel(ModelWithRequiredProperty model) => $"Hello {model.Prop}";
}

public class ModelWithRequiredProperty
{
[Required]
public required string Prop { get; set; }
}

namespace SimpleWebSiteWithWebApplicationBuilder
{
public partial class Program
Expand Down
Loading