When I am trying to access(view) a sharepoint image from asp.net application I am getting 401 Unauthorised error.

I am using following code: Dim webReq As WebRequest Dim webRes As WebResponse

    webReq = WebRequest.Create("imageUrl")
    webReq.UseDefaultCredentials = True
    webReq.PreAuthenticate = True
    webReq.Credentials = CredentialCache.DefaultCredentials

P.S I: I am able to view the image in the .net application from development server. Issue is when i hosted application to QA server. QA server is the Sharepoint server where image resides.


Apparently, when we are connecting from asp.net application to any other web application (in my case sharepoint) , by using above code the windows credentials are not passed.In order to pass the user windows credentials to the other web application , we need to use impersonation in code. In my case impersonation is disabled in IIS, but via code I temporarily enabled it.

 Dim winID As WindowsIdentity = 

    Dim ctx As WindowsImpersonationContext = Nothing


        ctx = winID.Impersonate()
        Dim request As HttpWebRequest = CType(WebRequest.Create(p1), HttpWebRequest)

        request.UseDefaultCredentials = True
        request.Method = "GET"
        request.PreAuthenticate = True           
        request.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials

            webRes = CType(request.GetResponse(), HttpWebResponse)

        Catch ex As Exception 

        End Try
    Catch ex As Exception 

    End Try

Your Answer

