Rediģēt

Kopīgot, izmantojot


ASP0007: Route parameter and argument optionality is mismatched

Value
Rule ID ASP0007
Category Usage
Fix is breaking or non-breaking Non-breaking

Cause

A route parameter is declared as required in the Delegate definition but is marked as optional in the endpoint route.

Rule description

When an endpoint is declared, optionality of parameters can be declared in both the route template and in the route handler arguments. When a parameter is declared as optional in the handler, it must also be declared as optional in the route template. For example, GET /todos fails to resolve a match for the following code:

app.MapGet("/todos/{id}", (int? id) => {});

The preceding code fails to match GET /todos because the id parameter was not provided, even though it is treated as optional in the route handler.

How to fix violations

To fix a violation of this rule, make sure that the optionality in the route template and the delegate match. For example, for the following code sample:

app.MapGet("/todos/{id}", (int? id) => {});

If the parameter is intended to be required, make the type non-nullable by removing the ? from int?:

app.MapGet("/todos/{id}", (int id) => {});

If the parameter is intended to be optional, then the nullable value type operator ? should be applied:

app.MapGet("/todos/{id?}", (int? id) => {});

When to suppress warnings

Do not suppress a warning from this rule. Mismatched parameter optionality can result in unexpected behavior with routing at runtime.