Georgi Koemdzhiev
Georgi Koemdzhiev

Reputation: 11931

How to redirect to a Controller/Action passing any URL parameters?

I am trying to implement "returnUrl" functionality in my aspnetcore app but I am struggelling to find a way to dynamically pass the parameters to an action.

The process flow goes like this:

enter image description here

  1. The user has bookmarked URL https://localhost:44358/Secure/VisualizationFiles?viz=vizFilePlays
  2. the website checks if they are logged in and if not redirects them to Home controller's Login action to log in (passing the returnUrl)
  3. after logging in the user is redirected to the originally requested URL above including any URL parameters

Right now the Secure controller methods use ActionFilterAttribute which intercept the incoming HTTP request and make sure the controller; the action and parameters get passed as returnUrl (or reRoute in that case)

public class NimsAuthenticationAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
         var url = filterContext.RouteData.Values["Controller"] + "/" + filterContext.RouteData.Values["Action"] + "?" + QueryString(filterContext.ActionArguments);
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary { { "controller", "Home" }, { "action", "Index" }, { "reRoute", url } });

        base.OnActionExecuting(filterContext);
    }

    private string QueryString(IDictionary<string, object> dict)
    {
        var list = new List<string>();
        foreach (var item in dict)
        {
            list.Add(item.Key + "=" + item.Value);
        }

        return string.Join("&", list);

    }

}

After the user gets redirected (from the secure controller) to the Home controller, we get the full returnUrl (i.e. reRoute URL) being passed

enter image description here

As you can see, right now I am doing some error-prone string manulupation to extract the Controller; Action and url params from the reRoute string. I would like to know:

Upvotes: 0

Views: 3481

Answers (1)

Jay Fridge
Jay Fridge

Reputation: 1057

You can use the Redirect Method instead of RedirectToAction.

So in you case it would look like this:

return Redirect("/" + reRoute);

The / is there to go to the root url, otherwise the request would route relative to the current controller.

Upvotes: 1

Related Questions