Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I change a route value then redirect to that route?
    primarykey
    data
    text
    <p>I have a UserAccountController that takes routes like this <code>"/{username}/{action}"</code>.</p> <p>I'd like to create some functionality so that I can take a user to an account-specific page without knowing their username up front. I'd like to be able to use the URL <code>"/your/{action}"</code> which would catch the fact that "your" was sent as their username, get their real username (because they are logged in), and redirect them to "/their-actual-username/{action}".</p> <p>I could do this in each of the controller actions, but I'd rather have it happen some place earlier that would do this for all of the controller actions. I attempted to do this in the Controller's <code>Initialize</code> method by changing the <code>RouteData.Values["username"]</code> to the real username then attempting to <code>Response.RedirectToRoute(RouteData); Response.End()</code> but that always took me to the wrong place (some completely wrong route).</p> <hr> <p><strong>Updated:</strong> Thanks to BuildStarted for leading me to this answer:</p> <pre><code>public class UserAccountController : Controller { protected override void OnActionExecuting(ActionExecutingContext filterContext) { base.OnActionExecuting(filterContext); if ((string) filterContext.RouteData.Values["username"] != "your") return; var routeValues = new RouteValueDictionary(filterContext.RouteData.Values); routeValues["username"] = UserSession.Current.User.Username; filterContext.Result = new RedirectToRouteResult(routeValues); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload