ASP.NET Core apps access HttpContext through the IHttpContextAccessor interface and its default implementation HttpContextAccessor. It's only necessary to use IHttpContextAccessor when you need access to the HttpContext inside a service.
ASP.NET Core applications access the HTTPContext through the IHttpContextAccessor interface. The HttpContextAccessor class implements it. You can use this class when you need to access HttpContext inside a service.
You have to get the host and path separately.
@Context.Request.Host
@Context.Request.Path
You need scheme, host, path and queryString
@string.Format("{0}://{1}{2}{3}", Context.Request.Scheme, Context.Request.Host, Context.Request.Path, Context.Request.QueryString)
or using new C#6 feature "String interpolation"
@($"{Context.Request.Scheme}://{Context.Request.Host}{Context.Request.Path}{Context.Request.QueryString}")
You can use the extension method of Request
:
Request.GetDisplayUrl()
This was apparently always possible in .net core 1.0 with Microsoft.AspNetCore.Http.Extensions
, which adds extension to HttpRequest
to get full URL; GetEncodedUrl.
e.g. from razor view:
@using Microsoft.AspNetCore.Http.Extensions
...
<a href="@Context.Request.GetEncodedUrl()">Link to myself</a>
Since 2.0, also have relative path and query GetEncodedPathAndQuery.
Use the AbsoluteUri property of the Uri, with .Net core you have to build the Uri from request like this,
var location = new Uri($"{Request.Scheme}://{Request.Host}{Request.Path}{Request.QueryString}");
var url = location.AbsoluteUri;
e.g. if the request url is 'http://www.contoso.com/catalog/shownew.htm?date=today' this will return the same url.
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