MVC动态路由 [英] MVC Dynamic Routes

查看:152
本文介绍了MVC动态路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建动态URL的路由控制器,一个ID值的行动。我用一个包罗万象的参数创建了以下路线

I would like to create dynamic urls that route to controller actions with an Id value. I've created the following route using a catch-all parameter

routes.MapRoute(
            "RouteName",                                                 
            "{id}/{*Url}",
            new { controller = "Controller", action = "Action", id = "" }
        );

这工作正常,并允许我使用以下URL:

This works as expected and allows me to use the following Urls:

http://website.com/1/fake/url/path(1为获取传递到操作方法的ID)

"http://website.com/1/fake/url/path" (1 being the id that gets passed to the action method)

有谁知道的方式来实现这种方式,而不是没有创造我自己的HTTP模块:

Does anyone know a way to achieve it this way instead without creating my own http module?:

http://website.com/fake/url/path/1

"http://website.com/fake/url/path/1"

感谢马克 -

推荐答案

路由重定向是基于路由表中的路由条目。它必须在系统的方式。例如,如果你有航作为后{控制器}customurl / ID/ {行动} / {ID}(MVC的默认设置)时,你会在网址框中输入customurl,它将把它的默认路由,无页将出现发现异常。所以,如果你婉使用自定义路径,然后先删除缺省路由。我这样做等。

Routes redirection is based on route entry in the route table. It must be in systematic way. For instance if you have route as "customurl/id" after {controller}/{action}/{id}(default of mvc) when you will enter "customurl" in the url box it will take it as default route and no page found exception will occur. So if you wan to use custom route then first remove the default route. I do this like.

RouteCollection routes = RouteTable.Routes;
                    if (routes["rname"] != null)
                    {
                        RouteTable.Routes.Remove(routes["rname"]);
                    }
                         routes.Remove(routes["Default"]);                           
                        routes.MapRoute(
                            name: "newname",
                            url: url + "/{customId}",
                            defaults: new { controller = "Search", action = "Index", customId = UrlParameter.Optional }
                            );

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

这篇关于MVC动态路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆