简体   繁体   中英

Authenticate against PHP webservice using C#

Here is the sample code for PHP Webservice client that works:

 $options = array();
 $options['trace'] = 1;   
 $options['login'] = 'username';
 $options['password'] = 'password';    
 $client = new SoapClient("http://wsurl.com/pt/wsdl", $options);

I would like to access this webservice using c# but having a hard time doing the authentication. Do I need to explicitly set the soap headers or there is a built in way to send credentials in .NET

There are two ways to do this because servers handle authentication differently. First you could use something like this:

var req = WebRequest.Create(<your url>);
NetworkCredential creds = new NetworkCredential(<username>, <password>);
req.Credentials = creds;

var rep = req.GetResponse();

However if you need an actual Authroization header you will want to use this code

public void SetBasicAuthHeader(WebRequest req, String userName, String userPassword)
{
 string authInfo = userName + ":" + userPassword;
 authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
 req.Headers["Authorization"] = "Basic " + authInfo;
}

And then your request code becomes

var req = WebRequest.Create(<your url>);
SetBasicAuthHeader(req, username, password);
rep = req.GetResponse();

Let me know if you have any questions.

If you add a service reference in your C# project, you can just call your service like this:

var proxy = new YourServiceClient();
proxy.ClientCredentials.UserName.UserName = "username";
proxy.ClientCredentials.UserName.Password = "password";

More information can be found here: http://msdn.microsoft.com/en-us/library/ms733775.aspx .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM