dotnet / dotnet/aspnetcore

[Analyzer] Warn on inconsistent constraints between route params and types

Open
#45,218 3 comments 0 reactions 1 assignee Claimed by @JamesNK View on GitHub
analyzer api-approved api-suggestion area-minimal area-mvc
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

Description

## Background and Motivation

It is possible to add constraints to route parameters that will never bind to an MVC or Minimal API action.

```csharp
app.MapGet("/product/{id:alpha}", (int id) => ...);
```
In the example above, alpha characters are never valid with an int route and will always fail.

## Proposed Analyzer

The analyzer should check for constraints inconsistent with the type being bound to and warn the user.

### Analyzer Behavior and Message

A route value that passes data type constraints such as datetime/alpha/bool errors when binding to int/double/decimal/etc:

```cs
app.MapGet("/{id:datetime}", (int id) => ...);
app.MapGet("/{id:alpha}", (int id) => ...);
app.MapGet("/{id:bool}", (int id) => ...);
```

And others like float/int/decimal constraints error when binding to bool/DateTime/etc.

Some number-based constraints require the parameter value is parsable as a number. That means they can't be bound to a DateTime, for example.

```cs
app.MapGet("/{id:min(10)}", (DateTime id) => ...);
```

The message should be:

> $"The constraint '{constraint}' on parameter '{parameter}' can't be used with type {typeName}."

### Category

- [ ] Design
- [ ] Documentation
- [ ] Globalization
- [ ] Interoperability
- [ ] Maintainability
- [ ] Naming
- [ ] Performance
- [ ] Reliability
- [ ] Security
- [ ] Style
- [x] Usage

### Severity Level

- [x] Error
- [ ] Warning
- [ ] Info
- [ ] Hidden

## Usage Scenarios

```cs
app.MapGet("/{id:datetime}", (int id) => ...);
app.MapGet("/{id:alpha}", (int id) => ...);
app.MapGet("/{id:bool}", (int id) => ...);
app.MapGet("/{id:min(10)}", (DateTime id) => ...);
app.MapGet("/{id:long}", (int id) => ...);
```

Should also work on MVC actions and Razor pages.

## Risks

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.