I am new to ASP.NET MVC and trying to learn new things while playing around with the following scenario, but didn't get it working.
Actually, I am trying to maintain a constant value parameter in the url for every request. Something similar when we have a session value in the url, after using <sessionState cookieless="true"/>
in Web.config file and it starts showing session value in this format
http://localhost:49961/(S(swl0ancynhWw2103jxm4ydwf))/Customer/Home
But I am trying to have a persistent parameter appended at the end of url for every request, like following link
http://localhost:49961/Customer/Home?constantVal=12345
This parameter is assumed to remain in url, whether I am using any HttpGet
or HttpPost
method.
So far I have tried re-writing the url using Application_BeginRequest()
inside Global.asax.cs file in following way:
void Application_BeginRequest(object sender, EventArgs e)
{
// Suppose Request.FilePath = /Customer/Home/UploadFile
// Unable to use "?constantVal" as required
Context.RewritePath(Request.FilePath + "/12345");
}
Action Method:
public ActionResult UploadFile(string id = null)
{
return View();
}
In the above way, although I am able to get value for id = "12345" in UploadFile Action, but neither it is showing in the url anywhere or it also require every HttpGet
method to have a receiving id parameter.
It's always nice to do something crazy so that you can better understand a system. :)
Is it possible to have a url parameter with a constant value through out the ASP.NET MVC application?
Yes.
However, your example (http://localhost:49961/Customer/Home?constantVal=12345
) will not work because the Route
class completely ignores query string values. It is possible to extend routing to make it query string aware, though.
By default, route values are 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 ASP.NET MVC 5 culture in route and url for an example of putting the culture into the URL, which preserves it between requests automatically.
That said, using RewritePath
in this context doesn't make any sense. RewritePath
changes the URL that the HTTP handler sees, not the URL in the browser that the user sees. In fact, since we have routing to map a request directly to a controller action, using RewritePath
in MVC really doesn't make sense at all. To change the URL that the user sees, you need to do a 302 or 301 redirect. See How to change route to username after logged in? for an example of redirecting to add a value to the URL automatically under a specific condition, which is similar to your use case.