C# 如何将url段作为参数发送到操作方法?

C# 如何将url段作为参数发送到操作方法?,c#,asp.net-mvc,asp.net-mvc-routing,C#,Asp.net Mvc,Asp.net Mvc Routing,在我的MVCWeb应用程序中,我要将所有带有一个url段的url路由到同一个控制器操作。例如: http://example.com/onePage 以下是我在控制器中的操作方法: public ActionResult SomeAction(string urlSegment) { ... } 现在,我希望url段(如示例中的“onePage”)作为输入发送到action方法 您可以显示MapRoute的外观以实现此目的吗?您可以通过编辑RouteConfig.cs文件来实现此目的: pu

在我的MVCWeb应用程序中,我要将所有带有一个url段的url路由到同一个控制器操作。例如:

http://example.com/onePage
以下是我在控制器中的操作方法:

public ActionResult SomeAction(string urlSegment)
{
...
}
现在,我希望url段(如示例中的“onePage”)作为输入发送到action方法


您可以显示MapRoute的外观以实现此目的吗?

您可以通过编辑RouteConfig.cs文件来实现此目的:

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

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

    routes.MapRoute(
        "CustomRoute",
        "{*urlSegment}",
        new { controller = "MyController", action = "SomeAction" }
    );
}
将MyController更改为任何控制器的名称


如果要精确匹配一个段,请删除
*

它可能看起来像这样

routes.MapRoute(
"UrlSegment", // Route name
"{urlSegment}", // URL with parameters
new { action="SomeAction",controller="ControllerName" }, // parameter defaults 
new[] { "Namespace.Controllers" } // controller namespaces);

我在打电话,所以很遗憾无法验证,但这应该得到你想要的

如果请求正好匹配一个
URLSEMENT
,那么该
*
不应该被删除吗?您是否看过以下内容: