dotnet / dotnet/aspnetcore

Minimal API with RequestDelegateGenerator: Nullable warnings generated when [AsParameters] + [FromBody] are used

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

Description

### Is there an existing issue for this?

- [x] I have searched the existing issues

### Describe the bug

Compiler warnings are generated if I use a record as the parameter of the route handler. The record has `[AsParameters]` annotated in the route parameter, and it contains a constructor parameter with `[FromBody]`.

The warnings are generated from `GeneratedRouteBuilderExtensions.g.cs`.

### Expected Behavior

No warnings should be generated since the framework does not allow `null` as the request body anyway.

### Steps To Reproduce

Create a project with `dotnet new webapiaot`. Replace the Program.cs with the following code:

```csharp
using Microsoft.AspNetCore.Mvc;
using System.Text.Json.Serialization;

var builder = WebApplication.CreateSlimBuilder(args);

builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonSerializerContext.Default);
});

var app = builder.Build();

app.MapPost("/test", ([AsParameters] TestClass test) => Results.Ok(test.TestBody));

app.Run();

[JsonSerializable(typeof(string))]
internal partial class AppJsonSerializerContext : JsonSerializerContext;

record TestClass([FromBody] string TestBody);
```

### Exceptions (if any)

```
1>C:\Users\yjn\source\repos\WebApplication3\WebApplication3\obj\Debug\net10.0\Microsoft.AspNetCore.Http.RequestDelegateGenerator\Microsoft.AspNetCore.Http.RequestDelegateGenerator.RequestDelegateGenerator\GeneratedRouteBuilderExtensions.g.cs(119,60,119,74): warning CS8604: Possible null reference argument for parameter 'TestBody' in 'TestClass.TestClass(string TestBody)'.
1>C:\Users\yjn\source\repos\WebApplication3\WebApplication3\obj\Debug\net10.0\Microsoft.AspNetCore.Http.RequestDelegateGenerator\Microsoft.AspNetCore.Http.RequestDelegateGenerator.RequestDelegateGenerator\GeneratedRouteBuilderExtensions.g.cs(146,60,146,74): warning CS8604: Possible null reference argument for parameter 'TestBody' in 'TestClass.TestClass(string TestBody)'.
```

### .NET Version

10.0.100-rc.1.25451.107

### Anything else?

There is a workaround to disable the nullable warnings for this parameter but it looks really ugly.

```csharp
record TestClass(
#nullable disable
[FromBody] string TestBody
#nullable restore
);
```

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.