Thursday, 3 September 2015

C#.NET reports "The request failed with HTTP status 401: Unauthorized" when accessing

We've recently seen an issue where C#.NET reports "The request failed with HTTP status 401: Unauthorized" when accessing a classic SOAP Web Reference.

The credentials are set using  CredentialCache.DefaultCredentials as shown in the code below.




/// <summary>
/// Starts the service.
/// </summary>
/// <remarks>The scheduler web service is not polled at start-up to improve start response times.</remarks>
public void StartService()
{
    try
    {
        server = new XIAAutomation();
        server.Credentials = CredentialCache.DefaultCredentials;
        server.Url = GetWebServiceUrl();
        server.Timeout = 60000;
        SetupTimer();
        Diagnostics.WriteEvent(String.Format(Resources.Service.StartupComplete, Assembly.GetExecutingAssembly().GetName().Version, server.Url), EventLogIdentifiers.Startup);
    }
    catch (Exception ex) { Diagnostics.WriteEvent(Resources.Service.StartupFailedException, EventLogIdentifiers.Startup, ex); }
}



 
The solution to this problem is to ensure that  the credentials are set after the URL


       
server.Url = GetWebServiceUrl();server.Credentials = CredentialCache.DefaultCredentials;


No comments:

Post a Comment