2

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).

2
  • Did you ever find a better way than the redirect-to-self? Commented Apr 1, 2020 at 13:12
  • Afaik, wasnt able to find a better solution. Commented Apr 2, 2020 at 17:30

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the prompt reply. Adding a parameter to the action wouldn't work for me, as I would want it to be available in the post back too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.