C# – SPSite in web service throws 401 error

asp.netcnetsharepointwss-3.0

I have this code:

using ( var site = new SPSite( myUrl ) ) {
    using ( var web = site.AllWebs[0] ) {
        // read-only operations
    }
}

The "myUrl" is top domain url with WSS 3.0. The authentication is set to Windows.
If I run this code from command-line under "external_app_user" account, all is fine. But if I run this code from webservice (outside of WSS webapplication), then result is http response "401 UNAUTHORIZED" instead of SOAP response. It's odd, because this code is in "try-catch" block, and if is any excception thrown I returned own error message in SOAP response.

The code is running on the same machine as WSS.

If I run the webservice from webbroser on the machine where web service is running, the classic windows login form is shown. If I run the webservice from webbrowser on another computer, I get only "401 UNAUTHORIZED" http response.

The web service is running under correct account. This account has access to the WSS (tested via sharepoint website). If i try get "System.Security.Principal.WindowsIdentity.GetCurrent().Name" the correct username is returned.

In web.config is set "<identity impersonate="true" userName="_my_username_" password="_my_password_" />.

Anyone has idea what is wrong?

Best Answer

The reason why you cannot catch the 401 is because SharePoint has custom handling for this exception, see this thread: Cannot catch the SharePoint Access denied error (including a suggestion how to turn it off).

Related Topic