Prevent NullReferenceException in case of missing Host
authorJoerg Rosenkranz <joerg.rosenkranz@gmail.com>
Fri, 10 Oct 2014 13:01:37 +0000 (15:01 +0200)
committerJoerg Rosenkranz <joerg.rosenkranz@gmail.com>
Fri, 10 Oct 2014 14:23:22 +0000 (16:23 +0200)
Do not throw a NullReferenceException when Host variable is not set.
Ignore the calls to RegisterObject and UnregisterObject instead.

mcs/class/System.Web/System.Web.Hosting/HostingEnvironment.cs
mcs/class/System.Web/Test/System.Web.Hosting/HostingEnvironmentTest.cs

index f5855311943f6ebd1be4c4157032aa5554d6a9f9..a2b87e029ce7335e0c190dc08f1959561b58b1bd 100644 (file)
@@ -160,7 +160,9 @@ namespace System.Web.Hosting {
                {
                        if (obj == null)
                                throw new ArgumentNullException ("obj");
-                       Host.RegisterObject (obj, false);
+
+                       if (Host != null)
+                               Host.RegisterObject (obj, false);
                }
 
                public static void RegisterVirtualPathProvider (VirtualPathProvider virtualPathProvider)
@@ -200,7 +202,9 @@ namespace System.Web.Hosting {
                {
                        if (obj == null)
                                throw new ArgumentNullException ("obj");
-                       Host.UnregisterObject (obj);
+
+                       if (Host != null)
+                               Host.UnregisterObject (obj);
                }
        }
 }
index eb3aa2a3e00a47fea106abd5e4626a9ccaadce65..2f039d028944852f305c9237c724d26dc550932b 100644 (file)
@@ -35,6 +35,10 @@ using System.Web.UI;
 using MonoTests.SystemWeb.Framework;
 
 namespace MonoTests.System.Web.Hosting {
+       public class MyRegisteredObject : IRegisteredObject {
+               public void Stop(bool immediate) {}
+       }
+
        [TestFixture]
        public class HostingEnvironmentTest {
                [Test]
@@ -105,6 +109,15 @@ namespace MonoTests.System.Web.Hosting {
                {
                        Assert.IsNull (HostingEnvironment.MapPath ("hola"));
                }
+
+               [Test]
+               public void RegisterAndUnregisterObject ()
+               {
+                       var registered = new MyRegisteredObject ();
+
+                       HostingEnvironment.RegisterObject (registered);
+                       HostingEnvironment.UnregisterObject (registered);
+               }
        }
 }
 #endif