【问题标题】:Website runs fine locally but crashes on Windows Azure网站在本地运行良好,但在 Windows Azure 上崩溃
【发布时间】:2014-03-15 16:19:23
【问题描述】:

我刚刚将我的应用程序发布到我的 Windows Azure 网站。 在我的网站上,我使用以下代码获取用户 IP 地址:

ip = HttpContext.Current.Request.UserHostAddress;

当我在 localhost 上运行它时它工作正常,但是当我在 Azure 上运行它时它崩溃 - 我什至尝试捕获异常,但它似乎没有抛出任何异常。

此外,当我远程调试网站时,我看不到 HttpContext 的“当前”属性 - 它只是说:

Cannot evaluate expression because the code of the current method is optimized.

此外,我可以看到我可以轻松获得控制器中的 IP - 问题仅在于我在控制器外部调用 HttpContext.Current.Request.UserHostAddress 时。

有谁知道问题出在哪里?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-4 azure web


    【解决方案1】:

    在使用 IIS 集成模式时,直到 Application_Start 完成运行后,HttpContext 才可用。

    要解决这个问题,您可以使用单例模式来读取设置并将其存储到应用程序回收为止。

    public class IPService
    {
        private static string ip = string.Emtpy;
    
        public static string GetIP()
        {
            if (string.IsNullOrEmpty(this.ip))
            {
                this.ip = HttpContext.Current.Request.UserHostAddress;
            }
    
            return this.ip;
        }
    }
    

    那么当你需要访问IP的时候,就可以调用:

    var ip = IPService.GetIP();
    

    请确保不要在应用程序启动期间调用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多