How to remove controller name from URL in MVC proj

2020-02-07 07:12发布

问题:

I have a URL like below and I need to remove the controller name (myController). I've use several fixes but none fixed the issue. Please help me guys..

http://foldername.example.com/foldername/myController/my-page

'example.com' is the domain and all the files related to the site is inside 'foldername' folder. 'my-page' is the view name

In the end I need the above URL to be like below.

http://example.com/my-page

Thank in advance guys..!!

回答1:

You could try inverting the routes definition by placing the more specialized route first. Also you probably didn't want to hardcode the action name as action but rather use the {action} placeholder:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        //routes.MapMvcAttributeRoutes();

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

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
   }
}

Follow the below links :

Link 1

Link 2

Link 3



回答2:

Enable attribute routing by adding following line before route.MapRoute in RouteConfig.cs file

routes.MapMvcAttributeRoutes();

Then add the Route Attribute to each action with the route name, like:

[Route("MyAction")]
public ActionResult MyAction()
{
...
}


回答3:

Use Routing in the global.asax

routes.MapRoute("MyAction", "{action}/{id}", new {controller = "MyController", action = "Index", id = UrlParameter.Optional});

and in controller

[Route("MyAction")]
public ActionResult MyAction()
{
 ...
 }

add following to RouteConfig.cs

routes.MapMvcAttributeRoutes();


回答4:

You should map new route in the global.asax (add it before the default one), for example:

routes.MapRoute("SpecificRoute", "{action}/{id}", new {controller = "MyController", action = "Index", id = UrlParameter.Optional});

routes.MapRoute("Default", "{controller}/{action}/{id}", new {controller = "Home", action = "Index", id = UrlParameter.Optional} );