asp.net-mvc ASP.NET MVC - 从 URL 中删除控制器名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3337372/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:23:45  来源:igfitidea点击:

ASP.NET MVC - Removing controller name from URL

asp.net-mvc

提问by James

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

我想从我的 URL 中删除控制器名称(对于一个特定的控制器)。例如:

http://mydomain.com/MyController/MyAction

http://mydomain.com/MyController/MyAction

I would want this URL to be changed to:

我希望将此 URL 更改为:

http://mydomain.com/MyAction

http://mydomain.com/MyAction

How would I go about doing this in MVC? I am using MVC2 if that helps me in anyway.

我将如何在 MVC 中执行此操作?如果这对我有帮助,我正在使用 MVC2。

回答by rrejc

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

您应该在 global.asax 中映射新路由(将其添加在默认路由之前),例如:

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

回答by niico

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

要在 2016 年 17 月 18 日更新此内容 - 最好的方法是使用属性路由。

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

在 RouteConfig.cs 中执行此操作的问题是旧路由也仍然有效 - 所以你将同时拥有

http://example.com/MyController/MyAction

http://example.com/MyController/MyAction

AND

http://example.com/MyAction

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.

有多个路由到同一页面对 SEO 不利 - 可能导致路径问题,并在整个应用程序中创建僵尸页面和错误。

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):

使用属性路由,您可以避免这些问题,并且更容易查看哪些路由位于何处。您所要做的就是将其添加到 RouteConfig.cs(可能在其他路由匹配之前位于顶部):

routes.MapMvcAttributeRoutes();

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

然后将路由属性添加到具有路由名称的每个操作中,例如

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

回答by Rahul

Here is the steps for remove controller name from HomeController

这是从 HomeController 中删除控制器名称的步骤

Step 1:Create the route constraint.

步骤 1:创建路由约束。

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.

第 2 步:
在使用我们刚刚创建的路由约束的默认映射之上添加一个新的路由映射。通用参数应该是您计划用作“根”控制器的控制器类。

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

现在您应该可以像这样访问您的家庭控制器方法:example.com/about、example.com/contact

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

这只会影响 HomeController。所有其他控制器将具有默认路由功能。

回答by sukru

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

您必须修改 MVC 的默认路由。ScottGu的博客里有详细的解释: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:

您应该更改的方法是 Application_Start。类似以下内容可能会有所帮助:

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.

路线的顺序很重要。它将在第一场比赛中停止。因此默认的应该是最后一个。

回答by Vijay S

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