【问题标题】:Access HttpContext in Application_Start ASP.NET MVC 4.0在 Application_Start ASP.NET MVC 4.0 中访问 HttpContext
【发布时间】:2013-02-01 21:15:55
【问题描述】:

我想访问我的主机并构建我的包。 我知道在 Application_start 中访问 httpcontext 并不直接。

您能否建议任何其他解决方法以在 RegisterBundles 方法中找到 Request.url.host

Global.asax

 protected void Application_Start()
        {
          BundleConfig.RegisterBundles(BundleTable.Bundles);
        }

BundleConfig.asax

public static string host { get; set; }
        public static string siteCssFileName { get; set;  }
        public static void RegisterBundles(BundleCollection bundles)
        {
host = "~";
            if (System.Web.HttpContext.Current.Request.Url.Host.Contains("local"))
                host = "http://localhost:xxx";
                else
                host=Request.url.host;
                bundles.Add(new StyleBundle("~/Content/jQuery/ui/css")
                  .Include(host+"/css/jQuery/hro-0079c1/jquery-ui-1.8.11.custom.css"));
         }

【问题讨论】:

    标签: asp.net-mvc-4 httpcontext application-start


    【解决方案1】:

    编辑:建议替代方法。

    这里有几种方法可以做到这一点:

    • 创建两个版本的捆绑包
    • 添加一个局部视图,检查Request.IsLocal 并呈现适当的包集
    • 从布局中调用局部视图

    另一种方法是创建一个 HtmlHelper 方法来为您解析路径。

    另一种方法是创建多个布局,并确定要在 viewstart 中使用的正确布局。

    实现这一点的方法有很多,这里就不多说了。

    【讨论】:

    • 我猜你推荐使用“LocalConstraint”类。但是我将如何调用这个“匹配”方法来获取“IsLocal”值
    • 对不起...我会澄清一下我的回答。
    • 那么,你是说不要使用这个BundleConfig.RegisterBundles(BundleTable.Bundles);在应用程序开始?
    • 不,继续注册。仅仅因为您创建了一个捆绑包并不意味着您必须在您的网站上使用它。
    【解决方案2】:

    由于我无法在 应用程序启动事件 中获取我的 Request 对象,我选择了以下方法来完成我的任务。 我只想知道我在应用启动活动中的主持人。

    1. 创建 Web.Config 转换
    2. 在每个环境中添加一个应用密钥,例如<add key="cdnReference" value="http://localhost:xxxx/" />
    3. 将应用启动事件中的密钥读取为cdnHost = ConfigurationManager.AppSettings["cdnReference"];

    【讨论】:

      猜你喜欢
      • 2011-08-23
      • 1970-01-01
      • 1970-01-01
      • 2011-10-22
      • 1970-01-01
      • 1970-01-01
      • 2017-09-17
      • 2010-12-27
      • 1970-01-01
      相关资源
      最近更新 更多