Analyzer: warn when marking a route parameter as optional if it isn't at the end of a route
- Dominant language
- C#
- Stars
- 38.4k
- Forks
- 10.9k
- Avg merge
- 2d 5h
- Merged PRs (30d)
- 276
Description
### Is your feature request related to a problem? Please describe.
Route parameters in an ASP.NET Core Web API can be marked as optional with a `?`, e.g.,
```csharp
app.MapGet("/test1/{foo?}", (string? foo) => foo ?? "none"); // "/test1" returns "none"
```
If a route parameter marked as optional is followed by a non-optional route segment, the optional annotation is ignored. E.g.,
```csharp
app.MapGet("/test2/{foo?}/bar", (string? foo) => foo ?? "none"); // "/test2//bar" returns 404
```
It is not immediately obvious (to me at least) that it would not be possible to have an optional parameter within a route, and there is no run-time error or warning when doing this.
The behavior appears to be the same for nullable value types (e.g. `int?`).
### Describe the solution you'd like
An analyzer that checks for routes containing optional parameters followed by non-optional route segments, and provides an appropriate warning.
I also couldn't find any mention in the documentation stating that this is not possible.
### Additional context
Optional route parameters _are_ allowed to be followed by other optional parameters, so the analyzer should consider this case. E.g.,
```csharp
app.MapGet("/test3/{foo?}/{bar?}", (string? foo, string? bar) => foo ?? bar ?? "none"); // "/test3" returns "none"
```
Related: #36637
Contributor guide
Assessment
This issue has not been assessed yet.