Search code examples
asp.net-core-mvcurl-routingasp.net-core-3.1

How to allow multiple Hyphen in action method name in mvc core 3.1?


I am working on an application in which requirements are to show url in following format for seo.

Initial format = www.abc.com/Home/OnlineShoppingInUk

Required format = www.abc.com/online-shopping-in-uk

I have done following changes in start.cs to hide controller name from url and controller name is removed from url

     endpoints.MapControllerRoute(
                    name: "onlineShoppingInUk",
                    pattern: "onlineShoppingInUk",
                    defaults: new { controller = "Home", action = "onlineShoppingInUk" });

and in home controller

     [Route("onlineShoppingInUk")]
     public IActionResult OnlineShoppingInUk()
    {
    ....
    }

But above method not works when url contains hyphen. I have tried following but online-shopping action method never calls and instead index method is called.

endpoints.MapControllerRoute(
                    name: "online-shopping-in-uk",
                    pattern: "online-shopping-in-uk",
                    defaults: new { controller = "Home", action = "online-shopping-in-uk" });

and in home controller

     [Route("online-shopping-in-uk")]
     public IActionResult OnlineShoppingInUk()
    {
    ....
    }

How to call an action method containing hyphens in Home controller ?


Solution

  • Please update your route config with below code.

    endpoints.MapControllerRoute(
                    name: "OnlineShoppingInUK",
                    pattern: "/online-shopping-in-uk",
                    defaults: new { controller = "Home", action = "OnlineShoppingInUK" });
    

    Remove Route from your method :

    public IActionResult OnlineShoppingInUK()
        {
        ....
        }
    

    And try this :

    www.abc.com/online-shopping-in-uk
    

    Also where your are calling this just use

    asp-route="OnlineShoppingInUK"