Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

c# - Static property always null in every request after set value on ASP.NET MVC5

I have a static class and static property

 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.

My Server use IIS 8.5 with Windows Server 2012 R2

Update1

There is no static constructor in the static class.

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

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

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);
        }

    }

Update 2

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);
                    }

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

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

Test.Tests = "Test";

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);
                        }

Now every request the log4net will output like this:

Test: Test

Now the Test new Value = Test3

Test: Test

Now the Test new Value = Test3

Test: Test

Now the Test new Value = Test3

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 .

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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 :-)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...