ASP。NET MVC通配符控制器任何参数路由

时间:2022-04-23 17:42:20

I want to have Controller/Action so that when I navigate to:

我想要有控制器/动作,当我导航到:

mysite.com/whatever. i type here will pipe into...a ! string.

public ActionResult Index(string anything)
{
    // anything = whatever. i type here will pipe into...a ! string.
    return View();
}

Do I need to setup a custom route?

我需要设置一个自定义路由吗?

I've tried this but it doesn't seem to handle periods, etc.

我试过了,但是好像经期不太长。

        routes.MapRoute(
            name: "Default",
            url: "{*anything}",
            defaults: new { controller = "Home", action = "Index" }
        );

1 个解决方案

#1


2  

If you constrain your route with a catch-all regex:

如果你用一套完整的正则表达式来约束你的路线:

routes.MapRoute(
    "Default",
    "{*anything}",
    new { controller = "Home", action = "Index" },
    new { anything = @"^(.*)?$" }
);

And ensure you have the UrlRoutingModule set up in your web.config with no precondition to ensure that even unmanaged requests (e.g. those deemed to have extensions) are put through the routing module, your catchall route should work fine.

并确保您的web上设置了UrlRoutingModule。在没有先决条件的情况下进行配置,以确保即使是不受管理的请求(例如那些被认为具有扩展的请求)也通过路由模块进行,您的catch - all路由应该可以正常工作。

#1


2  

If you constrain your route with a catch-all regex:

如果你用一套完整的正则表达式来约束你的路线:

routes.MapRoute(
    "Default",
    "{*anything}",
    new { controller = "Home", action = "Index" },
    new { anything = @"^(.*)?$" }
);

And ensure you have the UrlRoutingModule set up in your web.config with no precondition to ensure that even unmanaged requests (e.g. those deemed to have extensions) are put through the routing module, your catchall route should work fine.

并确保您的web上设置了UrlRoutingModule。在没有先决条件的情况下进行配置,以确保即使是不受管理的请求(例如那些被认为具有扩展的请求)也通过路由模块进行,您的catch - all路由应该可以正常工作。