Firstly, I would say if you need to keep the value throughout the session, then you should save it in the session and check that it is still valid on every call. This can be done using the custom action attribute that you add to the controller / required actions. If this value is necessary, then when the value is checked, you can change it to the login page or similar, if not, or it has expired.
In any case, it said that I thought I would have a crack to make it work. My first thought was to create a custom action attribute attribute that took the value of the query string and stored it in a session in OnActionExecuting , and then OnResultExecuted will add the key back to the query string. But since the QueryString in the query is a read-only collection, you cannot do this directly.
So what is now available to you?
Option # 1 - add it to all calls in Html.ActionLink () manually
or...
Option # 2 is to override the version of ActionLink that will automatically add you a value. This can be achieved like this. I would not recommend doing this though.
Start with a custom attribute.
public class PersistQueryStringAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { var sid = filterContext.RequestContext.HttpContext.Request.QueryString["sid"]; if (!string.IsNullOrEmpty(sid)) { filterContext.RequestContext.HttpContext.Session["sid"] = sid; } base.OnActionExecuting(filterContext); } }
All this is checking the request for request for the required key, and if available, add it to the session.
Then you redefine the way ActionLink extends to your own, which adds value.
public static class HtmlHelperExtensions { public static MvcHtmlString ActionLink<TModel>(this HtmlHelper<TModel> helper, string text, string action, string controller, object routeValues) { var routeValueDictionary = new RouteValueDictionary(routeValues); if (helper.ViewContext.RequestContext.HttpContext.Session["sid"] != null) { routeValueDictionary.Add("sid", helper.ViewContext.RequestContext.HttpContext.Session["sid"]); } return helper.ActionLink(text, action, controller, routeValueDictionary, null); } }
In each of the actions that will be called, apply an attribute (or apply it to the controller), for example:
[PersistQueryString] public ActionResult Index() { ViewData["Message"] = "Welcome to ASP.NET MVC!"; return View(); }
Note
As you enter the request value into the session, it will be applied to the life of the session. If you want to verify that this value is the same query, you will need to do some validation in the attribute overridden method.
Finally
I just did it as an exercise "can this be done." I would highly recommend against it.