I want to get the full URL, not just the Path
, not just the Query
, and not RouteValues
.
The entire URL as it has come in the raw form.
How can I do that in ASP.NET Core Razor Pages?
I want to get the full URL, not just the Path
, not just the Query
, and not RouteValues
.
The entire URL as it has come in the raw form.
How can I do that in ASP.NET Core Razor Pages?
5
Answers
You can use the
PageLink
method ofIUrlHelper
to get the absolute URL to a page.In the page handler (or controller),
IUrlHelper
can be accessed via theUrl
property:If you want to generate a URL to a controller action, use
ActionLink
.Works in ASP.NET Core 3.0 and above.
You can use the
UriHelper
extension methodsGetDisplayUrl()
orGetEncodedUrl()
to get the full URL from the request.Usage:
You could create an extension class to use the
IHttpContextAccessor
interface to get theHttpContext
. Once you have the context, then you can get theHttpRequest
instance fromHttpContext.Request
and use its propertiesScheme
,Host
,Protocol
etc. as in:For example, you could require your class to be configured with an
HttpContextAccessor
:Which is something you can do in your
Startup
class (Startup.cs file):You could probably come up with different ways of getting the
IHttpContextAccessor
in your extension class, but if you want to keep your methods as extension methods in the end you will need to inject theIHttpContextAccessor
into your static class. (Otherwise, you will need theIHttpContext
as an argument on each call).You can try to use
HttpContext.Request.Scheme + HttpContext.Request.Host
to gethttps://localhost:xxxx
,then useHttpContext.Request.Path + HttpContext.Request.QueryString
to get path and query:You can do it by this way. In
.net core