Search code examples
c#asp.net-mvcroutesblogsrouteconfig

Change route string url of blog from controller/action/{*Url} to {*Url}


I have my personal blog site which was done using Asp.Net MVC and C# language.

As I have configured RouteConfig with "controller/action/{*Url}" for blog URL where {*Url} could be any text.

Now I want to change the Url pattern from "controller/action/{*Url}" to {*Url}.

Example:

From below Url

https://abcd.co.in/home/newsdetail/abcd-xyz-opqr-stu

To

https://abcd.co.in/abcd-xyz-opqr-stu

I have done the following changes

routes.MapRoute("", "mycontroller/myactionmethod/{*Url}", new { controller = "Home", action = "NewsDetail", Url = "" });

But it is calling every time URL hits my domain.

Please suggest what are the possible solutions that will not affect other functionality or URLs and it should fulfill my requirements.

Thanks in advance.


Solution

  • After a few google search and R&D on Attribute-based routing I have come up with one solution:

    Steps:

    1. Need to define that I am using Attribute routing

      routes.MapMvcAttributeRoutes();
      
    2. Remove existing route entry for the Action method.

    3. Set Attribute route entry path above the Action method.

      [Route("{Url}")]

    4. Just update the URL in href from previous to just URL.

    From

    <a href="/home/newsdetail/@item.Url"> 
    

    To

    <a href="/@item.Url">