How to get URL in Razor View in the form /Controller/Action/Id/.../QueryString

Viewed 193

I have a form which passes the current url to a controller action so that it redirects the user back to the page he/she previously was.

Currently, I am concatenating the Controller, Action and QueryString as follows;

var currentUrl = $"/{ViewContext.RouteData.Values["controller"]}/{ViewContext.RouteData.Values["action"]}/{Context.Request.QueryString}";

In my controller action I have the following;

if (Url.IsLocalUrl(returnUrl))
    return Redirect(returnUrl);
else
    return RedirectToAction("Index", "Home");

I feel as if this is rigid and that there is probably a method which already does this but I can't figure out what it is. The approach I was using does not accomodate for instances like /Home/Index/1/2019/...?message=hello.

1 Answers

You can try to add parameters to routing.Here is a demo:

startup(The quantity of your parameters(/1/2019/...) needs to be less than or equal to the quantity of /{id?}/{id1?}/{id2?}/... ):

 app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}/{id1?}/{id2?}");
            });

View:

<h1>
    CurrentUrl:@Context.Request.Path@Context.Request.QueryString
</h1>

result: enter image description here

Related