Why is nullable int id parameter always null in ASP.NET Core web app?

103 Views Asked by At

This is an ASP.NET Core 6 MVC web application with the following controller method that isn't working as expected:

[Route("Edit/{id:int?}")]
[HttpGet]
public async Task<ActionResult> Edit(int? id){....}

Calling this endpoint with a url like controllername/Edit/1 or controllername/Edit?id=1 both result in the id being null. If I change it to be an int instead of an int?, it works fine.

What's wrong with that method signature and route?

This route configuration is in my Program.cs file.

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Login}/{action=Index}/{id?}");

    endpoints.MapRazorPages();
});
1

There are 1 best solutions below

1
steve v On

You have put the ? in the wrong place in your route constraint. int? is not a supported constraint.

If you want to mark the parameter as optional for purposes of routing, use id?:int

[Route("Edit/{id?:int}")]
[HttpGet]
public async Task<ActionResult> Edit(int? id){....}