简体   繁体   中英

ASP.Net Core ReturnURL when using a CDN?

Setup

An ASP.Net Core MVC website upgraded from Core 2.2 to ASP.Net Core 3.1. It has just been moved behind a CDN. All on Azure specifically.

The public url, pointing (via CNAME) at the CDN, is www.sitename.com. The backend server url, which the CDN points at is coreaz.sitename.com.

Everything is https, and seems to be working pretty well. CDN and core site have appropriate certs.

Problem

The ReturnUrl in various places is composed with:

Context.Request.GetEncodedUrl()

that returns https://coreaz.sitename.com/currentpage?params=abc That was perfect before putting the CDN in the middle of everything. Now, as soon as someone hits a page via return url, they are bypassing the CDN for the rest of their visit.

Question

What's the correct way to now generate https://www.sitename.com/currentpage?params=abc in pages to point at the CDN?

The code is opensource, and I'd like to keep it flexible so someone else can host it easily.

Seems like I need to have an application setting with PreferredHostName set to www.sitename.com.

But then the composition of the URL seems to be messy. I suspect I'm missing something easy.

I ended up using this method to recompose the URI, in a SettingsService class.

    public string GetPreferredUri(HttpRequest request)
    {
        var preferredhost = _config["PreferredHost"];
        if (!String.IsNullOrWhiteSpace(preferredhost))
        {
            request.Host = new HostString(preferredhost);
        }

        var absoluteUri = string.Concat(
                    request.Scheme,
                    "://",
                    request.Host.ToUriComponent(),
                    request.PathBase.ToUriComponent(),
                    request.Path.ToUriComponent(),
                    request.QueryString.ToUriComponent());

        return absoluteUri;
    }

And I call that from a .cshtml page:

[...]
@inject SettingsService settingsService

[...]

<a class="nav-link pt-0" asp-area="" asp-controller="Account" asp-action="Login"
       asp-route-returnUrl="@settingsService.GetPreferredUri(Context.Request)">Log in</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM