How to remove controller name from URL in MVC proj

2020-02-07 07:10发布

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..!!

4条回答
家丑人穷心不美
2楼-- · 2020-02-07 07:38

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} );
查看更多
相关推荐>>
3楼-- · 2020-02-07 07:45

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

查看更多
够拽才男人
4楼-- · 2020-02-07 07:49

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()
{
...
}
查看更多
Fickle 薄情
5楼-- · 2020-02-07 08:00

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();
查看更多
登录 后发表回答