如何生成与MVC3 HTTPS绝对URL? [英] How to Generate absolute urls with https in MVC3?

查看:111
本文介绍了如何生成与MVC3 HTTPS绝对URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用MVC3,我试图从服务HTTPS内容,问题是,当我叫Url.Content的文件仍从http使用相对URL服务。我认为这个问题在MVC3是写给但我似乎无法找到任何解决方案。有谁知道,如果这个问题在本质上MVC3解决,如何实现它,或者我需要创建自己的helper方法来生成基于协议的绝对URL?

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 this problem was addressed in MVC3 but i can't seem to find any solution. Does anybody know if this issue is inherently solved in MVC3 and how to accomplish it or do I need to create my own helper methods to generate absolute Urls based on protocol?

推荐答案

您可以通过大概的 VirtualPathUtility.ToAbsolute 。大概是这样的:

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);
  }
}

你会使用类似:

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

(没有测试此我自己,随意摆弄,使其工作的权利。)

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

这可以帮助你来生成内容文件绝对路径。为了改变所产生的URL的方案,你可以创建一个操纵给定的URL方案的附加扩展方法,使他们HTTPS,或别的东西。

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.

由于哈立德在评论中指出,类似的扩展方法有多种开源项目已经可用,您可以使用(因为该许可证允许)。一个例子可以找到<一个href=\"http://www.google.com/$c$csearch/p?hl=en#MEucUyOL2vo/trunk/Suteki.Shop/Suteki.Common/Extensions/UrlExtensionsHelper.cs&q=SSL%20package%3ahttp://sutekishop%5C.google$c$c%5C.com&d=4\">here.

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.

这篇关于如何生成与MVC3 HTTPS绝对URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆