skip to Main Content

I have a project that I am working on that was done in ASP.NET MVC 5.

They used the default URL structure that comes standard with the framework. For example, the AGM page was constructed like this:

  • Controller: Home
  • Action method: AGM

Without any routing setup, to access this page, you would need to go to the following URL:

www.example.com/Home/AGM

This is the URL that they sent to the press. This URL looks horrible and I want to implement a cleaner URL structure which will look like this:

www.example.com/agm

I have set it up like this in the RouteConfig.cs file:

routes.MapRoute(
    name: "AGM",
    url: "agm",
    defaults: new { controller = "Home", action = "AGM" }
);

What I want to achieve is if the user types in www.example.com/Home/AGM then it needs to display the URL like www.example.com/agm. Instead, it displays like www.example.com/Home/AGM.

I’m not sure how to implement this?

2

Answers


  1. Configure routing and define action in the url

    routes.MapRoute(
        name: "AGM",
        url: "{action}",
        defaults: new { controller = "Home", action = "AGM" }
    );
    

    Then in the AGM method redirect to www.example.com/agm

    if (Request.Path.ToLower() == "/home/agm")
    {
        return Redirect("/agm");
    }
    
    Login or Signup to reply.
  2. You can simply add [Route("AGM")] and [Route("Home/AGM")] top of your Action method:

    [Route("AGM")]
    [Route("Home/AGM")]
    public IActionResult AGM()
    {
        return View();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search