How to call an ASP.NET web service with username/password from C#?
Posted: (EET/GMT+2)
If you have an ASP.NET web service that requires authentication credentials, you need a way to supply these in your client application. It can be difficult to find an easy answer from the .NET SDK documentation, so I'm giving a basic example here.
Shortly put, you need to use the NetworkCredential class from the System.Net namespace to supply the credentials. Additionally, you can use a class called CredentialCache to store an URL/credentials pair which your web service interface can consume. If you have a web service interface named "MWS" (for My Web Service), you can setup the credentials for Basic of Digest authentication, along with a timeout (always a good idea) with the following code:
private static void SetupWebServiceCall(
My_Web_Service_Interface mws)
{
NetworkCredential cred = new NetworkCredential(
"username", "password", "domain");
CredentialCache cache = new CredentialCache();
cache.Add(new Uri(mws.Url), "Basic", cred);
mws.Credentials = cache;
mws.Timeout = 15*1000; // 15 seconds
}
If you call this setup method before doing anything else with the SOAP interface, you get the properly set up authentication plus control over the timeout period. Of course, you would store the username and password somewhere for security instead of in the source code, but you'll get the idea.