dotnet / dotnet/aspnetcore

SystemTextJsonValidationMetadataProvider enfore use of JsonPropertyNameAttribute when FromHeaderAttribute in use

Open
#64,135 0 comments 0 reactions 0 assignees View on GitHub
area-mvc
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

### Describe the bug
I noticed that after specifying **ModelMetadataDetailsProviders** (specifically - `SystemTextJsonValidationMetadataProvider`) `JsonPropertyNameAttribute` is required in some cases

**Basic example**
Configuration: [Program.cs](https://github.com/issue-poc/SystemTextJsonValidationMetadataProvider/blob/fc1a4ac15aa31b6ffb753381bc88625e4e1fa0f0/Program.cs#L9)
```csharp
builder.Services.AddControllers(o => o.ModelMetadataDetailsProviders.Add(new SystemTextJsonValidationMetadataProvider()));
```

Data model [PagingParams.cs](https://github.com/issue-poc/SystemTextJsonValidationMetadataProvider/blob/fc1a4ac15aa31b6ffb753381bc88625e4e1fa0f0/PagingParams.cs#L9-L12)
```csharp
[MaxLength(16384)]
[JsonPropertyName("x-sc-continuation")] //change value to replicate the issue.
[FromHeader(Name = "x-sc-continuation")]
public string? ContinuationTokenHeader { get; init; } = null;
```

When I have the same value of `Name` in `FromHeader` attribute and `JsonPropertyName` attribute everything works fine. But when `JsonPropertyName` is undefined or has different value I always get 400 error when requesting API.

```json
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"errors": {},
"traceId": "00-5650230aee41367c2657a23411e3e9c1-6a5def53af55fe88-00"
}
```

The value set here
https://github.com/dotnet/aspnetcore/blob/06a440549690d5dba8e3501c21c61907da69a733/src/Mvc/Mvc.Core/src/ModelBinding/Metadata/SystemTextJsonValidationMetadataProvider.cs#L65
when `JsonPropertyName` is undefined is `continuationTokenHeader` (lower-cased property name)

### To Reproduce
```
git clone git@github.com:issue-poc/SystemTextJsonValidationMetadataProvider.git
cd SystemTextJsonValidationMetadataProvider
dotnet watch
```

**happy path** - all works fine
```powershell
Invoke-RestMethod -Uri "http://localhost:5202/weatherforecast" -Headers @{"x-sc-continuation"="dGVzdDE="} -Method Get
```

**bug?** - 400 response code
modify `PagingParams.cs` - change `JsonPropertyName` value and wait for rebuild
run the same request again
```powershell
Invoke-RestMethod -Uri "http://localhost:5202/weatherforecast" -Headers @{"x-sc-continuation"="dGVzdDE="} -Method Get
```

---
**JsonPropertyName** attribute in my case is a workaround. I had no need to define it before.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.