如何在MVC3中使用https生成绝对网址? [英] How to Generate absolute urls with https in MVC3?

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

问题描述

我正在使用 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生成绝对网址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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