Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 511
Joe Audette Avatar asked Mar 18 '16 11:03

Joe Audette


People also ask

How do I redirect to another page in net core?

You can use any of the following methods to return a RedirectResult: Redirect – Http Status Code 302 Found (temporarily moved to the URL provided in the location header) RedirectPermanent – Http Status Code 301 Moved Permanently. RedirectPermanentPreserveMethod – Http Status Code 308 Permanent Redirect.

How do I get the relative URL in HTML?

To link pages using relative URL in HTML, use the <a> tag with href attribute. Relative URL is used to add a link to a page on the website. For example, /contact, /about_team, etc.


2 Answers

There is an extension method for that: Request.GetDisplayUrl(); that returns https://localhost/MyController/MyAction?Param1=blah.

Or the encoded version Request.GetEncodedUrl()

To any of them you must add: using Microsoft.AspNetCore.Http.Extensions;

like image 34
Gerardo Grignoli Avatar answered Oct 10 '22 07:10

Gerardo Grignoli


Do you mean Context.Request.Path?

I quickly made a sample project with a HomeController, an Index.cshtml and a Second.cshtml. The Second.cshtml looks like:

@addTagHelper "*, Microsoft.AspNet.Mvc.TagHelpers"
<h1>@ViewBag.Title</h1>
<a asp-controller="Home" asp-action="Index" asp-route-returnUrl="@Context.Request.Path">Log in</a>

And the anchor tag renders to the browser as (tested with Chrome dev tools):

<a href="/?returnUrl=%2FHome%2FSecond">Log in</a>

You have Request.Query and/or Request.QueryString to concatenate the full URL.

You could make an extension method on the HttpRequest class to for instance return the Path and the QueryString together if you wish.

like image 176
Danny van der Kraan Avatar answered Oct 10 '22 08:10

Danny van der Kraan