問題描述
我正在使用 MVC3 并嘗試從 https 提供內(nèi)容,問題是當(dāng)我調(diào)用 Url.Content 時(shí),仍然使用相對 url 從 http 提供文件.我認(rèn)為這個(gè)問題在 MVC3 中得到了解決,但我似乎找不到任何解決方案.有誰知道這個(gè)問題是否在 MVC3 中固有地解決了,以及如何完成它,還是我需要?jiǎng)?chuàng)建自己的輔助方法來生成基于協(xié)議的絕對 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);
}
}
你會(huì)像這樣使用:
@Url.Absolute(Url.Content("~/Content/Image.png"))
(我自己沒有對此進(jìn)行測試,請隨意嘗試使其正常工作.)
(Didn't test this myself, feel free to play around to make it work right.)
這有助于您為內(nèi)容文件生成絕對 URL.為了更改生成的 URL 的方案,您可以創(chuàng)建一個(gè)額外的擴(kuò)展方法來操作給定 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 在評論中指出的那樣,您可以使用的各種開源項(xiàng)目中已經(jīng)提供了類似的擴(kuò)展方法(如果許可證允許).可以找到一個(gè)示例 這里.
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.
這篇關(guān)于如何在 MVC3 中使用 https 生成絕對 URL?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!