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?
CodePudding user response:
You can use the PageLink
method of IUrlHelper
to get the absolute URL to a page.
In the page handler, IUrlHelper
can be accessed via the Url
property:
public async Task<IActionResult> OnPostAsync()
{
string url = Url.PageLink("/PageName", "PageHandler", routeValues);
...
}
If you want to generate a URL to a controller action, use ActionLink
.
CodePudding user response:
You can use the UriHelper
extension methods GetDisplayUrl()
or GetEncodedUrl()
to get the full URL from the request.
GetDisplayUrl()
Returns the combined components of the request URL in a fully un-escaped form (except for the QueryString) suitable only for display. This format should not be used in HTTP headers or other HTTP operations.
GetEncodedUrl()
Returns the combined components of the request URL in a fully escaped form suitable for use in HTTP headers and other HTTP operations.
Usage:
using Microsoft.AspNet.Http.Extensions;
...
string url = HttpContext.Request.GetDisplayUrl();
// or
string url = HttpContext.Request.GetEncodedUrl();
CodePudding user response:
You could create a extension class to use the IHttpContextAccessor interface to get the HttpContext. Once you have the context, then you can get the HttpRequest instance from HttpContext.Request and use its properties Scheme, Host, Protocol etc as in:
string scheme = HttpContextAccessor.HttpContext.Request.Scheme;
For example, you could require your class to be configured with an HttpContextAccessor:
public static class UrlHelperExtensions
{
private static IHttpContextAccessor HttpContextAccessor;
public static void Configure(IHttpContextAccessor httpContextAccessor)
{
HttpContextAccessor = httpContextAccessor;
}
public static string AbsoluteAction(
this IUrlHelper url,
string actionName,
string controllerName,
object routeValues = null)
{
string scheme = HttpContextAccessor.HttpContext.Request.Scheme;
return url.Action(actionName, controllerName, routeValues, scheme);
}
....
}
Which is something you can do on your Startup class (Startup.cs file):
public void Configure(IApplicationBuilder app)
{
...
var httpContextAccessor =
app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
UrlHelperExtensions.Configure(httpContextAccessor);
...
}
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 the IHttpContextAccessor into your static class. (Otherwise you will need the IHttpContext as an argument on each call)