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
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.
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.
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With