How to Generate absolute urls with https in MVC3?

前端 未结 4 1759
天命终不由人
天命终不由人 2020-12-16 12:40

I am using MVC3 and am trying to serve content from https, the problem is that when I call Url.Content the files are still served from http using a relative url. I thought t

4条回答
  •  暖寄归人
    2020-12-16 13:01

    You can probably implement your own solution using VirtualPathUtility.ToAbsolute. Probably something like this:

    public static class UrlHelperExtension {
      public static string Absolute(this UrlHelper url, string relativeOrAbsolute) {
        var uri = new Uri(relativeOrAbsolute, UriKind.RelativeOrAbsolute);
        if (uri.IsAbsoluteUri) {
          return relativeOrAbsolute;
        }
        // At this point, we know the url is relative.
        return VirtualPathUtility.ToAbsolute(relativeOrAbsolute);
      }
    }
    

    which you would use like:

    @Url.Absolute(Url.Content("~/Content/Image.png"))
    

    (Didn't test this myself, feel free to play around to make it work right.)

    This helps to you to generate absolute URLs for your content files. In order to change the scheme of the resulting URLs, you can create an additional extension method that manipulates the scheme of the given URLs so that they are HTTPS, or something else.

    As Khalid points out in the comments, similar extension methods are already available in various open-source projects which you can make use of (given that the license permits). An example one can be found here.

提交回复
热议问题