是否可以在 ASP.NET MVC 应用程序中使用具有恒定值的 url 参数?

Is it possible to have a url parameter with a constant value through out the ASP.NET MVC application?

我是 ASP.NET MVC 的新手,尝试在尝试以下场景的同时学习新事物,但没有成功。

实际上,我试图在 url 中为每个请求维护一个常量值参数。当我们在 url 中有一个会话值时,在 Web.config 文件中使用 <sessionState cookieless="true"/> 之后,它开始以这种格式显示会话值

http://localhost:49961/(S(swl0ancynhWw2103jxm4ydwf))/Customer/Home

但我试图在每个请求的 url 末尾附加一个持久参数,例如 link

http://localhost:49961/Customer/Home?constantVal=12345

无论我使用的是HttpGet还是HttpPost方法,这个参数都假定保留在url中。

到目前为止,我已尝试使用 Global.asax.cs 文件中的 Application_BeginRequest() 按以下方式重写 url:

void Application_BeginRequest(object sender, EventArgs e)
{
    // Suppose Request.FilePath = /Customer/Home/UploadFile
    // Unable to use "?constantVal" as required
    Context.RewritePath(Request.FilePath + "/12345");
}

操作方法:

public ActionResult UploadFile(string id = null)
{
    return View();
}

通过上述方式,虽然我能够在 UploadFile 操作中获取 id = "12345" 的值,但它在 url 任何地方都没有显示或者它还要求每个 HttpGet 方法都有一个接收 id 参数。

做一些疯狂的事情总是好的,这样你才能更好地理解一个系统。 :)

Is it possible to have a url parameter with a constant value through out the ASP.NET MVC application?

是的。

但是,您的示例 (http://localhost:49961/Customer/Home?constantVal=12345) 将不起作用,因为 Route class 完全忽略了 查询字符串值。不过 extend routing to make it query string aware 是可以的。

默认情况下,路由值为 automatically reused from the current request, so if you put a value there, it will just "stick" from one request to the next if all of the URLs on the site are built with the UrlHelper (or function that uses the UrlHelper, such as ActionLink). See ,例如将文化放入 URL,这会在请求之间自动保留它。

就是说,在此上下文中使用 RewritePath 没有任何意义。 RewritePath 更改了 HTTP 处理程序看到的 URL,而不是用户看到的浏览器中的 URL。事实上,由于我们有路由将请求直接映射到控制器动作,所以在MVC中使用RewritePath真的没有任何意义。要更改用户看到的 URL,您需要执行 302 或 301 重定向。有关在特定条件下自动向 URL 添加值的重定向示例,请参阅 ,这与您的用例相似。