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();
});
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