Friday, July 23, 2010

ASP.NET MVC – Object Reference is not set to an instance of an object

July 23, 2010 Posted by Jason Irwin , , , 2 comments

In the end I have to chalk this down to incompetence and one of those frustrating error messages that tell you absolutely nothing.

I’ve been working on an ASP.NET MVC application and last night decided to use JQTouch to provide an iPhone/Android mobile interface. Doing so should have been extremely straightforward. The planned steps were as follows:

Add code in my base ViewEngine to detect if a mobile browser is being used. If so, provide a mobile view rather than a standard one.

  • Create a number of views that use the JQTouch library to format my pages for mobile devices.


I recently came across the Mobile Browser Definition File on Codeplex which can be dumped in the app_browser folder in an solution in order to provide a bunch of information through Request.Browser. I dumped this into my solution, updated my view engine and implemented a few views with JQTouch. It didn’t take too long and i was feeling pretty good. However, attempting to open my application  I received a very generic error:


Object reference not set to an instance of an object

As shown in the below screenshot, not only is the message completely useless, but no source file or code line is specified.




I debugged for ages, but couldn’t even break in the global.asax file – so couldn’t step through the code to see what was going on. I subsequently tore my code apart, and after a full rollback realized that the mobile.browser file that I had dumped in my app_browser folder was causing the error.


Removing this file allowed my application to run, re-adding it caused the message to re-appear. After a little googling I found the root cause – browser files can no longer go straight into the app_browser folder – they must go in a sub-folder…any sub-folder. Had I looked a little closer I would have seen the following on the MDBF FAQ page and saved myself a ton of time and frustration:

Why am I getting "Object reference not set to an instance of an object."?
If after copying the .browser file into your AppBrowsers folder you get a compile error “Object reference not set to an instance of an object.” and you have .NET 3.5 SP1, then the issue is likely that you must create a sub-directory (of any name) in your AppBrowsers folder and place the .browser file in there. E.G. \App_Browsers\MobileBrowserData\mobile.browser

And now all is back to normal