简体   繁体   English

获取没有url参数的MVC路由路径

[英]Get MVC Route Path without url parameters

In my MVC4 project I have an url http://domain.com/ {controller}/{action}/. 在我的MVC4项目中,我有一个URL http://domain.com/ {controller} / {action} /。 To determine what page user visits and and get current active menuitem I use url path like this HttpContext.Request.Url.AbsolutePath.ToLower() 为了确定哪些页面用户访问并获得当前活动的菜单项,我使用像HttpContext.Request.Url.AbsolutePath.ToLower()这样的网址路径

However in some cases paths are /{controller}/{action}/{id} etc. which are actually /{controller}/{action}/?{id}=value . 但是,在某些情况下,路径是/ {controller} / {action} / {id}等,实际上是/ {controller} / {action} /?{id} = value

How can I get /{controller}/{action}/ without parameters if they are overridden by routing rules? 如果参数被路由规则覆盖,如何不带参数获取/ {controller} / {action} /

Thank you. 谢谢。

Are you only interested in the controller and action names? 您仅对控制器和动作名称感兴趣吗?

If so, use the RouteData property of the controller. 如果是这样,请使用控制器的RouteData属性。

You can use it like this: 您可以像这样使用它:

public ActionResult Index()
{
    var controller = this.RouteData.Values["controller"];
    var action = this.RouteData.Values["action"];
}

How about adding one new route before your current route which will be like this. 如何在当前路线之前添加一条新路线,就像这样。

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

new route will be like this - 新路线将是这样-

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

Please note that you need to add this route before your current route in RouteConfig.cs . 请注意,您需要在RouteConfig.cs中的当前路由之前添加此路由 This is because MVC starts searching routes in RouteConfig file from top to bottom. 这是因为MVC从顶部到底部开始搜索RouteConfig文件中的路由。 As soon as it finds any matching route it will stop searching further. 一旦找到任何匹配的路由,它将停止进一步搜索。 So for your problem when there will be route without param it will pick "Withoutparam" route. 因此,对于您的问题,当有没有参数的路线时,它将选择“ Withoutparam”路线。

As I can understand from your comment below. 从下面的评论中我可以理解。 You need url without id in every condition. 在每种情况下,您都需要不带id的url。 If it's so, then I think you can do this: - 如果是这样,那么我认为您可以这样做:-

var url = new StringBuilder();

string[] partOfUrl = HttpContext.Request.Url.AbsolutePath.ToLower().split('/');

for(int count = 0; count< (partOfUrl.Length - 1); count++) 
{   
   url.Append(partOfLength[count] + "/") 
}

use url.ToString() as url which you want. 使用url.ToString()作为所需的URL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM