开发者

ASP.NET MVC - Removing controller name from URL

开发者 https://www.devze.com 2023-01-08 18:04 出处:网络
I want to remove the controller name from my URL (for one specific controller). For example: http://mydomain.com/MyController/MyAction

I want to remove the controller name from my URL (for one specific controller). For example:

http://mydomain.com/MyController/MyAction

I would want this URL to be changed to:

http://mydomain.com/MyAction

How would I go about doing this in MVC? I am using MVC2 if that开发者_如何学Python helps me in anyway.


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});

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


To update this for 2016/17/18 - the best way to do this is to use Attribute Routing.

The problem with doing this in RouteConfig.cs is that the old route will also still work - so you'll have both

http://example.com/MyController/MyAction

AND

http://example.com/MyAction

Having multiple routes to the same page is bad for SEO - can cause path issues, and create zombie pages and errors throughout your app.

With attribute routing you avoid these problems and it's far easier to see what routes where. All you have to do is add this to RouteConfig.cs (probably at the top before other routes may match):

routes.MapMvcAttributeRoutes();

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

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


Here is the steps for remove controller name from HomeController

Step 1: Create the route constraint.

public class RootRouteConstraint<T> : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        var rootMethodNames = typeof(T).GetMethods().Select(x => x.Name.ToLower());
        return rootMethodNames.Contains(values["action"].ToString().ToLower());
    }
}

Step 2:
Add a new route mapping above your default mapping that uses the route constraint that we just created. The generic parameter should be the controller class you plan to use as your “Root” controller.

routes.MapRoute(
    "Root",
    "{action}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    new { isMethodInHomeController = new RootRouteConstraint<HomeController>() }
);

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

Now you should be able to access your home controller methods like so: example.com/about, example.com/contact

This will only affects HomeController. All other Controllers will have the default routing functionality.


If you want it to apply to all urls/actions in the controller (https://example.com/action), you could just set the controller Route to empty above ApiController. If this controller going to be your starting controller, you'll also want to remove every launchUrl line in launchSettings.json.

[Route("")]
[ApiController]


You'll have to modify the default routes for MVC. There is a detailed explanation at ScottGu's blog: http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx

The method you should change is Application_Start. Something like the following might help:

RouteTable.Routes.Add(new Route(
  Url="MyAction"
  Defaults = { Controller = "MyController", action = "MyAction" },
  RouteHandler = typeof(MvcRouteHandler)
}

The ordering of the routes is significant. It will stop on the first match. Thus the default one should be the last.


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

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

精彩评论

暂无评论...
验证码 换一张
取 消