Error 401 Unauthorized Exception with Managed Client Object Model on ASP.NET website

I am trying to access a file permission from a separate ASP.NET web application using Managed Client Object Model. Since I need to get the user’s permission I have to use CredentialCache.DefaultCredentials. Everything runs fine using Visual Studio debug mode but I hit the following error when I host the site on IIS (same as SharePoint but difference web app)


[WebException: The remote server returned an error: (401) Unauthorized.]
DocViewer._default.Page_Load(Object sender, EventArgs e) in C:\Users\administrator\Documents\Visual Studio 2010\Projects\SharePointDocViewer\DocViewer\default.aspx.vb:174
System.Web.UI.Control.OnLoad(EventArgs e) +132
System.Web.UI.Control.LoadRecursive() +66
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2428

Most blogs on the web suggested instantiating a new NetworkCredential but that is not the way to go for my case.

I eventually solved the problem by setting the App Pool of the ASP.NET to be that of the SharePoint app pool. Below is fragment of my code using SPCOM.


Using client As ClientContext = New ClientContext(Request.QueryString("portalUrl"))
Try
client.Credentials = System.Net.CredentialCache.DefaultCredentials
Dim web = client.Web
Dim file As SharePoint.File = web.GetFileByServerRelativeUrl(Request.QueryString("fileUrl"))
Dim item As ListItem = file.ListItemAllFields

client.Load(item, Function(i) i.EffectiveBasePermissions)
client.ExecuteQuery()