Skip to content

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

@captainsafia

Description

@captainsafia

Background and Motivation

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

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:

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.

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
  • Usage

Severity Level

  • Error
  • Warning
  • Info
  • Hidden

Usage Scenarios

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

Metadata

Metadata

Assignees

Labels

analyzerIndicates an issue which is related to analyzer experienceapi-approvedAPI was approved in API review, it can be implementedapi-suggestionEarly API idea and discussion, it is NOT ready for implementationarea-minimalIncludes minimal APIs, endpoint filters, parameter binding, request delegate generator etcarea-mvcIncludes: MVC, Actions and Controllers, Localization, CORS, most templates

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions