55 lines
1.9 KiB
Markdown
55 lines
1.9 KiB
Markdown
---
|
|
title: "ASP0007: Route parameter and argument optionality is mismatched"
|
|
description: "Learn about analysis rule ASP0007: Route parameter and argument optionality is mismatched"
|
|
author: safia
|
|
monikerRange: '>= aspnetcore-6.0'
|
|
ms.author: riande
|
|
ms.date: 10/21/2021
|
|
uid: diagnostics/asp0007
|
|
---
|
|
# 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:
|
|
|
|
```csharp
|
|
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:
|
|
|
|
```csharp
|
|
app.MapGet("/todos/{id}", (int? id) => {});
|
|
```
|
|
|
|
If the parameter is intended to be required, make the type non-nullable by removing the `?` from `int?`:
|
|
|
|
```csharp
|
|
app.MapGet("/todos/{id}", (int id) => {});
|
|
```
|
|
|
|
If the parameter is intended to be optional, then the [nullable value type](/dotnet/csharp/language-reference/builtin-types/nullable-value-types) operator `?` should be applied:
|
|
|
|
```csharp
|
|
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.
|