How to get current app relative url for login redirect in ASP.NET Core

Viewed 7042

I'm trying to implement simple logic so that whatever page a user is on in a site is where the user will get redirected back to after login. To do that it seems I need an easy way to get the relative url of the current request.

I tried using the full url with a link like this in my _LoginPartial.cshtml:

<a asp-controller="Login" asp-action="Index" asp-route-returnUrl="@Context.Request.GetEncodedUrl()">Log in</a>

but that results in an error:

A URL with an absolute path is considered local if it does not have a host/authority part. URLs using virtual paths ('~/') are also local.

Seems like there should be a simple built in method for getting the current relative url. Am I missing something or do I need to implement my own extension method for this? I'm using RC1

3 Answers

To get both relative path and query string in ASP.NET Core 2.0 or later, you can use an extension method of HttpRequest called GetEncodedPathAndQuery().

UriHelper.GetEncodedPathAndQuery(HttpRequest) Method

To use this method in your Razor view, please add @using Microsoft.AspNetCore.Http.Extensions either in your Razor view or in _ViewImports.cshtml.

Your <a> tag would then be:

<a asp-controller="Home" asp-action="Index" 
   asp-route-returnUrl="@Context.Request.GetEncodedPathAndQuery()">Log in</a>
Related