Solving "Access denied" exceptions in WebServices
This morning I wrote the NUnit test class for a WebService method I am currently building. This method stores data in different data stores and uses other webservices to do this. All these services were running on my machine. But when I started NUnit, the test failed when I tried to make a call to one of the other webservices. All I got was: System.Net.WebException: The request failed with HTTP status 401: Access Denied.
Why was I getting this? I checked the access to the directories, to make sure the ASPNET account had enough access rights, and that was OK. Same for the IUSR account. So I tried to call the webmethod by viewing the .asmx file in the webbrowser. That worked, so why was my webservice getting an Access denied result when my webservice called that method? The code seemed to be fine:
public int GetCustomerId(string name)
{
int customerId = -1;
WebserviceCustomer.Interface customer = new WebserviceCustomer.Interface();
customerId = customer.GetCustomerIdByName(name);
return customerId;
}
This made me check the internet to see what might be the problem. What I found was that, even when the user credentials are all correct and identical, you need to set the credentials before making the actual call to the other webservice. This posting in particular on http://www.dotnet247.com pointed me to the solution. The code now looks like this:
public int GetCustomerId(string name)
{
int customerId = -1;
WebserviceCustomer.Interface customer = new WebserviceCustomer.Interface();
// Make sure the credentials for the webservice call are the current credentials
customer.Credentials = System.Net.CredentialCache.DefaultCredentials;
customerId = customer.GetCustomerIdByName(name);
return customerId;
}