Search code examples
asp.net-core.net-coreasp.net-core-mvc

Setting route parameter automatically in ASP.NET Core


Considering the scenario where a specific identifier should be stored after authentication and kept within the path as long as the user is authorized with no need to be specified each time I redirect from the back-end.

To be more specific, When a user signs in, their username (the identifier in this example) is stored as a claim. Now, all of their operations should be under https://example.com/{username}/.....
The problem arising here is that, as far as I know, I need to pass this username each time I generate a URL via the IUrlHelper or redirect through IActionResults.

Does ASP.NET Core provide any standard API for this scenario?
If not, supposing I have to improvise, what are some possible workarounds for this issue?

NOTE: The example above is meant to describe the issue; the reasons behind this method and the benefits it brings are a different story.

Thank you all in advance!


Solution

  • You may try URL rewrite, follow this document

    A minimal example:

        public static class MethodRules
        {
            public static void RedirectAuthenticatedUser(RewriteContext context)
            {
                
                var isauthenticated = context.HttpContext.User.Identity?.IsAuthenticated;
                var iscontained = context.HttpContext.Request.RouteValues.ContainsKey("username");
                if (isauthenticated == true&&!iscontained)
                {
                    var username = context.HttpContext.User.Identity.Name;
                    var request = context.HttpContext.Request;
                    var response = context.HttpContext.Response;
                    response.StatusCode = (int)HttpStatusCode.MovedPermanently;
                    context.Result = RuleResult.EndResponse;
                    response.Headers[HeaderNames.Location] =
                        "/"+username + request.Path + request.QueryString;
                }
                
            }
        }
    

    In program.cs:

        ......
    
        app.UseAuthorization();
        
        var options = new RewriteOptions().Add(MethodRules.RedirectAuthenticatedUser);
        app.UseRewriter(options);
        app.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
        
        app.MapControllerRoute(
            name: "auth",
            pattern: "{username}/{controller=Home}/{action=Index}/{id?}");
        
        app.MapRazorPages();
    

    Result:

    enter image description here