Generate HTTPS link in Web API using Url.Link

2019-04-04 19:23发布

I need to generate an absolute url to an ASP.NET Web API for a later callback/redirection.

The link can be generated using

Url.Link("RouteName", new { controller = "Controller", action = "Action" });

This returns the correct Url, however, I need it to always be https. Url.Link appears to generate a url using the scheme of the current request. For example, if the request generating the url is something like http://www.myhost.com/controller/generateUrl then Url.Link generates an http url. If the request generating the url is https://www.myhost.com/controller/generateUrl then Url.Link generates an https url.

The url needs to always be generated using https. Is there a parameter or route value that can be passed to Url.Link to achieve this?

Thanks.

1条回答
对你真心纯属浪费
2楼-- · 2019-04-04 20:05

It doesn't seem possible with Url.Link()

I would check the HttpRequest and change it to https to get all Url.Link() to return an https link.

Something like:

        if (Url.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
        {
            var secureUrlBuilder = new UriBuilder(Url.Request.RequestUri);
            secureUrlBuilder.Scheme = Uri.UriSchemeHttps;
            Url.Request.RequestUri = new Uri(secureUrlBuilder.ToString());
        }

        // should now return https
        Url.Link("RouteName", new { controller = "Controller", action = "Action" });
查看更多
登录 后发表回答