ASP.NET MVC Url.Action 将当前路由值添加到生成的 url [英] ASP.NET MVC Url.Action adds current route values to generated url

查看:14
本文介绍了ASP.NET MVC Url.Action 将当前路由值添加到生成的 url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 SO 中多次看到这个问题,但没有一个给出任何可接受的答案:

I have seen this question a couple of times here in SO but none of them with any acceptable answer:

ASP.NET MVC @Url.Action 包含当前路由数据
ASP.NET MVC 隐式添加路由值

基本上我有一个控制器,它有一个名为 Group 的操作方法,它有一个重载,它不接收参数并显示一个元素列表,另一个重载接收一个 id 并显示该组的详细信息.

Basically I have Controller with an action method called Group, it has an overload that receives no parameters and displays a list of elements and another one that receives an id and displays details for that group.

如果我这样做:

Url.Action("Group", "Groups");

从网站的主页 (/) 返回这样的网址:

From the main page of the site (/) it returns an url like this:

"mysite.com/Groups/Group"

没关系现在,如果站点的当前地址是/Groups/Group/1我调用相同的方法

which is alright Now, if the current address of the site is /Groups/Group/1 And I call the same method

Url.Action("Group", "Groups");

返回的网址是这样的:

"mysite.com/Groups/Group/1"

生成 URL 时自动添加当前页面的路由值.即使我以这种方式生成 URL:

It automatically adds the value of the route for the current page when generating the URL. Even if I generate the URL this way:

Url.Action("Group", "Groups", null);

因此明确指定我不想要任何路由值,生成的 URL 是相同的.要获取我想要的地址,我必须将路由值显式设置为空字符串,如下所示:

Thus explicitly specifying that I don't want any route values, the generated URL is the same. To get the address I want I have to explicitly set the route value to an empty string, like so:

Url.Action("Group", "Groups", new {id=""});

这将生成以下网址:

"mysite.com/Groups/Group"

我的问题是,为什么会发生这种情况?如果我没有设置任何路由值,它就不应该将它们添加到生成的 URL 中.

My question is, why does this happen? If I don't set any route values it shouldn't add them to the generated URL.

推荐答案

Url.Action 将重用当前的请求参数,如果你没有明确设置它们.它是在出站 url 匹配算法中设计的.在生成url的过程中查找路由数据参数时,参数取自:

Url.Action will reuse the current request parameters, if you do not explicitly set them. It is by design in outbound url-matching algorithm. When looking for the route data parameters in a process of generating url, parameters are taken from:

1) 明确提供的值

2) 来自当前请求的值

2) values from the current request

3) 默认值

按照我上面指定的顺序.

In the order I specified above.

路由的出站匹配算法很复杂,因此像您在示例中所做的那样,显式设置请求的所有参数是一种很好的做法

Outbound matching algorithm for routes is complicated, so it is good practice to explicitly set all parameters for request, as you did in your example

这篇关于ASP.NET MVC Url.Action 将当前路由值添加到生成的 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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