静态属性始终空在ASP.NET MVC5设定值后,每一个请求 [英] Static property always null in every request after set value on ASP.NET MVC5

查看:154
本文介绍了静态属性始终空在ASP.NET MVC5设定值后,每一个请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个静态类静态属性

 public static class Test
 {
     public static string Tests { get; set; }
 }

现在的问题是,我有一个控制器一个动作

Now the problem is, I have a Action in a Controller

public ActionResult SomeActionInController(){
         ``              ``
     //  this place always execute in every request
     if (null == Test.Tests)
          Test.Tests = "some value";
         ``              ``
}

不过,我会得到的在每一个请求,而不是本地调试,只在服务器上

But I will get null in every requests, not local debug, only on the server.

我看到这么多的人说:静态属性值将会保持在整个应用程序域,但为什么会这样呢?是否有固定它什么办法?谢谢你。

I saw so many people said : Static property value will keeping on whole application domain, But why this is happening now ? Is there any way to fixed it? Thank you.

我的服务器使用 IIS 8.5 Windows Server 2012中R2

UPDATE1

没有静态构造函数中的静态类。

There is no static constructor in the static class.

如果我将请求发送到行动,空会发生每一次,因为我可以看到它使用 log4net的

if I send request to the Action, the null will happen every time, because I can see it use log4net.

我已经禁用空闲超时和空闲的时间了,所有设置为0 。因此,有没有回收的问题。

I already disable Idle time out and free time out, all set to 0. So there is no recycle problem.

这是我的Global.asax:

This is my Global.asax:

public class MvcApplication : System.Web.HttpApplication
    {
        private readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(MvcApplication));

        protected void Application_Start()
        {
            Elmah.Mvc.Bootstrap.Initialize();
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);


            // Setting log4net
            log4net.Config.XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(Server.MapPath("~/log4net.config")));


            // Only keep Razor
            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new RazorViewEngine());



            System.Threading.Tasks.Task.Factory.StartNew(new Action(() =>
            {
                try
                {
                    System.Threading.Thread.Sleep(1000 * 100 * 1);

                    // Send a fake request for warm up the website, when after it recycle
                    WebClient webClient = new WebClient();
                    using (Stream stream = webClient.OpenRead(ConfigurationManager.AppSettings["InitialPath"]))
                    {
                        if (stream.CanRead)
                        {
                            log.Debug("Success warm up when recycle");
                        }
                        else
                        {
                            log.Debug("warm up failed");
                        }
                    }



                }
                catch (WebException ex)
                {
                    log.Debug(ex);
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                }
            }));

        }


        /// <summary>
        /// Setting Page Language
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Application_AcquireRequestState(object sender, EventArgs e)
        {
            if (HttpContext.Current != null && HttpContext.Current.Session != null)
            {
                if (AdminLanguage == 1)
                {
                    Thread.CurrentThread.CurrentCulture = new CultureInfo("xx-xx");
                    Thread.CurrentThread.CurrentUICulture = new CultureInfo("xx-xx");
                }
                else
                {
                    Thread.CurrentThread.CurrentCulture = new CultureInfo("xx-xx");
                    Thread.CurrentThread.CurrentUICulture = new CultureInfo("xx-xx");
                }
            }
        }


        /// <summary>
        /// Cache setting
        /// </summary>
        /// <param name="context"></param>
        /// <param name="arg"></param>
        /// <returns></returns>
        public override string GetVaryByCustomString(HttpContext context, string arg)
        {
            // cache from DevTrends.MvcDonutCaching
            if (arg == "NavStatic")
            {
                return "NavStatic=" + HttpContext.Current.Session.SessionID;
            }

            return base.GetVaryByCustomString(context, arg);
        }

    }

更新2

我将每一次设置,因为我用这个code,所以不要担心。

I will set it every time, because I use this code, So don't worry about it.

       if (string.IsNullOrEmpty(Test.Tests))
                    {
                        log.Debug("Test: null, this time it will be setting");
                        Test.Tests = "Test";
                    }
                    else
                    {
                        log.Debug("Test: " + Test.Tests);
                    }

和服务器上,log4net的将输出它时,每一个请求(进入动作):

And on the server, The log4net will output it when every request(access the action) :

测试:空,这个时候它会被设置

Test: null, this time it will be setting

测试:空,这个时候它会被设置

Test: null, this time it will be setting

测试:空,这个时候它会被设置

Test: null, this time it will be setting

UPDATE3

有关的一些朋友建议我把一些code在的Application_Start()

For some friends advice I put some code in the Application_Start()

Test.Tests = "Test";

所以,现在,每一个请求会得到成功的价值。 但是,我改变我的code本在行动:

So now, every request it will successful get the value. But I change my code to this in Action:

if (string.IsNullOrEmpty(Test.Tests))
                        {
                            log.Debug("Test: null, this time it will be setting");
                            Test.Tests = "Test";
                        }
                        else
                        {
                            log.Debug("Test: " + Test.Tests);
                            Test.Tests = "Test3";
                            log.Debug("Now the Test new Value = " + Test.Tests);
                        }

现在每一个请求log4net的将输出是这样的:

Now every request the log4net will output like this:

测试:测试

现在测试新值= Test3的

Now the Test new Value = Test3

测试:测试

现在测试新值= Test3的

Now the Test new Value = Test3

测试:测试

现在测试新值= Test3的

Now the Test new Value = Test3

但是,这不是我想要的。我想静态属性可以读取和修改在整个应用程序域,而不是只有1次。

But that's not what I want. I want the static property can be read and modify in whole application domain, not only 1 time .

推荐答案

乔治·斯托克经过讨论和戴夫·贝克尔,守信调试。而终于找到了问题的根源是:只是因为我的创建log4net的日志文件到网站bin文件夹。那么当每个请求进来,log4net的写日志,和IIS检测有)一些文件更改,则Application_End(将执行。都没有了。

After discussion with George Stocker and Dave Becker , And keeping debug it. And finally find the problem source is: just because I create the log4net log file into the website "Bin" folder. then when every request come in, log4net write the log, and IIS detect there is some file changed, then The Application_End() will execute. all gone.

感谢这2 firends。

Many thanks these 2 firends.

如果你有同样的问题,不要把所有的或创建的任何文件,斌文件夹,或者试图写它。除非你想申请的破坏你可以做到这一点: - )

If you has a same problem, don't every put or create any file to "Bin" folder, or trying to write it. Unless you want application destroyed you can do it :-)

这篇关于静态属性始终空在ASP.NET MVC5设定值后,每一个请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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