Reputation: 7472
I am trying to write a custom ActionFilter
which will append a request id to the QueryString
if it doesn't already have one.
Something like this :
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
Controller controller = (Controller)filterContext.Controller;
HttpRequestBase request = filterContext.HttpContext.Request;
// New request
if (request.QueryString[REQUEST_ID_KEY] == null)
{
string requestId = Utility.GetNewUniqueId();
controller.Session[REQUEST_ID_KEY] = requestId;
////////////////////////////////////////
// Add request id to query string ...???
////////////////////////////////////////
return;
}
}
One way to add the parameter to the query string which I found was to redirect the action to itself with the request id added to the route values, like this :
RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
redirectTargetDictionary.Add("action", actionName);
redirectTargetDictionary.Add("controller", controllerName);
redirectTargetDictionary.Add(REQUEST_ID_KEY, requestId);
filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
But this kind of seems like a hack. Is there a better way to add parameters to the QueryString
? (note that my aim is to achieve a ActionFitler
which rewrites urls, so I have to pass the parameter in the QueryString
).
Upvotes: 2
Views: 5098
Reputation: 44906
I believe that by the time the routing engine has been engaged you won't be able to re-write URLs. Routing doesn't really work that way.
You can however manipulate the action values that get used to invoke an Action by using a filter. Phil Haack has an article explaining this exact approach.
Upvotes: 1