Search code examples
c#asp.net-mvcasp.net-core.net-corerazor

Why is asp-route-id helper not mapping in accordance with my RouteAttribute template?


I have a ASP.NET CORE endpoint with a RouteAttribute:

[HttpGet]
[Route("MyController/MyAction/{id}")]
public async Task<IActionResult> GetAsync(int id, string rc)
{
    ...

Notice that I'm expecting id to be passed as a part of the URL, and rc to be passed as a query string.

And I have an MVC razor page that is supposed to be using the anchor helpers to create a link to this controller:

@foreach (var item in Model)
{
    <a asp-controller="MyController" asp-action="MyAction"
        asp-route-id="@item.Id" [email protected]>Execute</a>
}

I'd expect this to create an anchor with the link:

http://localhost:5000/MyController/MyAction/1?rc=234

But instead it creates an anchor with the link:

http://localhost:5000/MyController/MyAction?id=1&rc=234

In other words, it's sending id as a query string, and not as part of the URL, despite the template declaration in the RouteAttribute.

Any ideas as to why?


Solution

  • you have to configure the endpoints like this in your startup if you want it works the way you want

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

    When you use id in default route, html helper put the id value in your default route at id place. You can use another name instead of id. And then you can use this name in html helpers. Not default names are adding to the url as a query string parameters.

    if in your startup

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    
    });
    

    then you are supposed to use mostly attribute routing