Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate HTTPS link in Web API using Url.Link

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.

like image 921
Chrisgh Avatar asked Jun 16 '14 15:06

Chrisgh


1 Answers

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" });
like image 195
Trisk Avatar answered Oct 12 '22 02:10

Trisk