How to change the value of a route and then redirect to that route?

I have a UserAccountController that takes routes like this "/{username}/{action}".

I would like to create some functionality so that I can take the user to the account page without knowing my username. I would like to be able to use a URL "/your/{action}"that would catch the fact that “your” was sent as his username, get his real username (since they are logged in) and redirect them to "/ their-actual -username / { act}".

I could do this in each of the controller actions, but I would prefer it to happen earlier, which would do for all controller actions. I tried to do this in the Controller method Initialize, changing RouteData.Values["username"]to the real username and then trying Response.RedirectToRoute(RouteData); Response.End(), but it always led me to the wrong place (some completely wrong route).


Updated: Thanks BuildStarted for taking me to this answer:

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);
    }
}
+3
source share
1 answer

You can use FilterAttribute with an IActionFilter to accomplish what you want.

public class UserFilterAttribute : FilterAttribute, IActionFilter  {
    public void OnActionExecuted(ActionExecutedContext filterContext) {
    }

    public void OnActionExecuting(ActionExecutingContext filterContext) {
        var username = filterContext.RouteData.Values["username"];
        var realUserName = ""; //load from database
        filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new { controller = "Users", action = "Index", username = realUserName }));
    }
}

Then on your ActionResult in your controller, you can apply [UserFilter]to the action.

[UserFilter]
public ActionResult UnknownUserHandler() {
    return View();
}

, . , , :)

+5

Source: https://habr.com/ru/post/1765868/


All Articles