我正在使用 MVC3 并尝试从 https 提供内容,问题是当我调用 Url.Content 时,仍然使用相对 url 从 http 提供文件.我认为这个问题在 MVC3 中得到了解决,但我似乎找不到任何解决方案.有谁知道这个问题是否在 MVC3 中固有地解决了,以及如何完成它,还是我需要创建自己的辅助方法来生成基于协议的绝对 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 的方案,您可以创建一个额外的扩展方法来操作给定 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.
正如 Khalid 在评论中指出的那样,您可以使用的各种开源项目中已经提供了类似的扩展方法(如果许可证允许).可以找到一个示例 这里.
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!