Generating an absolute URL while ignoring all ambient values
See original GitHub issueIs there a simple way to generate an URL to the current Razor page, while ignoring all ambient values?
Let’s assume I’m on a Razor page Foo
that has an optional route parameter id
, @page {id?}
. So my current URL is http://localhost:5000/Foo/Bar
. Now I want to generate a link to that same Razor page but without the id
. The desired result would be http://localhost:5000/Foo
.
All my attempts to use the IUrlHelper
failed because it will always reuse the ambient values, even when I specify an explicit RouteValueDictionary
. That’s because the UrlHelper will eventually use the link generator to create an address, and that will always extract the ambient values first.
The only way I got this to work now is the following:
public static string GetPageUri(this HttpContext httpContext, string page)
{
var linkGenerator = httpContext.RequestServices.GetService<LinkGenerator>();
var values = new RouteValueDictionary
{
["page"] = page,
};
return linkGenerator.GetUriByAddress(httpContext, new RouteValuesAddress
{
ExplicitValues = values,
}, values);
}
So I use the link generator and the most low-level function it offers to create an URI by a RouteValuesAddress
where I explicitly leave out the ambient values.
Am I missing something or is there really no way to generate a link like that from the UrlHelper directly? I am aware that reusing ambient values for the same page is completely per design but there should still be some way to opt out of this, or not?
Issue Analytics
- State:
- Created 4 years ago
- Comments:7 (7 by maintainers)
Top GitHub Comments
@poke I see.
I’m going to close the issue for now as the question has been answered. I’ll let @rynowak comment on the fragment below if he has any further thoughts and we can potentially open a separate issue if necessary to track any remaining work.
Super yes. The problem is that we have many many experiences that are layered on top of it, and these areas are super touchy.