The Web application at XXX could not be found when using SharePoint OM in an ASP.NET WebApplication on 64 bit server

When using SharePoint 2010 Server OM code in an ASP.NET web application on a Windows 2008 64 bit server, you get below exception :

The Web application at https://servername:portnumber/sitename/ could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application.

You are using a very simple code and the exception occurs at the very first line while opening new instance of an SPSite :

 using (SPSite osite = new SPSite("https://blrs2r11-1c/"))
        {
            using (SPWeb oweb = osite.OpenWeb())
            {
               // Response.Write(oweb.Title);
                Label1.Text = oweb.Title;
            }
        }
 

Well, if it was a console application, then setting Output type as Any CPU\x64 and target build as .Net 3.5 will work :

https://blogs.msdn.com/b/sowmyancs/archive/2010/04/01/filenotfoundexception-the-web-application-at-http-url-could-not-be-found.aspx

However, this is an ASP.NET web application\website type of project.

Please note that the issue is not specific to any specific version of SharePoint or Visual Studio as such, because it’s more to do with the fact that this behavior is

only when SharePoint is on a 64 bit server.Here' are some observations that I would like to enlist regarding this error :

Are you trying F5 debugging of your asp.net webapplication? If yes, you would always get the error because the built in ASP.Net Development server (WebDev.WebServer.exe) a.k.a Cassini is a 32 bit process while SharePoint is 64 bit.

If you however host the website\webapplication under IIS,then you should be able to use the code , if you take care of the following :

1. App Pool identity of the asp.net webapplication has rights over SharePoint - preferably make them identical

2.And IIS Website is using windows authentication (failing which, You would get 401 unauthorized exception while accessing SPWeb's instance variable's properties. Surprisingly, not at OpenWeb()).