Home > Enterprise >  Url.Action routes to the wrong controller
Url.Action routes to the wrong controller

Time:11-04

I have two controllers, one Web API controller and the other a MVC controller. These two controllers have the same name and the same action name, though the one in API controller is a post while the one in MVC is a get, as shown here.

This is the API controller:

[Route("api/[controller]")]
public class SameNameController : ControllerBase
{  
    [HttpPost]
    public IEnumerable<*className*> SameNameAction([FromBody] *typeName*[] data)
    {
       // Detail implementation
    }
}

And this is the MVC controller:

public class SameNameController: Controller
{
    public ActionResult SameNameAction(int? page, int? pageSize)
    {
       //Detail implementation
    }    
}

I'm using X.PagedList to generate pagination. When I click any of pages, I receive an error

HTTP 405 - this page isn't working

Upon further inspection, I realized that the URL generated is the issue.

Here is the problematic part of the view.

@Html.PagedListPager((IPagedList)Model, page => Url.Action("SameNameAction", "SameNameController", new { page, pageSize= 5}))

Here is the routing definition in program.cs. As you can see, it's just basic stuff.

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

I expect that Url.Action would generate an url to the get action of the MVC controller. Instead, it generates an url to the post action of the Web API controller.

This is what I got:

<a href="/api/SameNameController?page=2&amp;pageSize=5">2</a>

This is what I expect:

<a href="/SameNameController/SameNameAction?page=2&PageSize=5">2</a>

I've never experienced Url.Action generating routing to an API controller. I'm not sure this is due to pagelist combined with url.action or url.action alone.

I can change the action name of the API controller, and the URL is generated as expected. However, this is not the issue. I would like to know why it map to the API controller and not the MVC controller to begin with.

CodePudding user response:

I expect that Url.Action would generate an url to the get action of the MVC controller. Instead, it generates an url to the post action of the Web API controller.

Based on your scenario, I have checked your code between the line. As you know enter image description here

Hope it will guide you accordingly.

  • Related