Calling a PHP webservice from c#

2020-03-26 06:58发布

问题:

I am currently trying to call a PHP web service in c#. I have been trying dozens of solutions I have found on the internet, but with no luck, and none which have the same issue as me. I am unfamiliar with PHP.

I can successfully call authenticate_get from my c#

string auth_id = client.authenticate_get("www.testexample.com", "e5d30c56d600a7456846164");

and get the authentication id returned, but then don't know how to pass the array in c#. Here is PHP example given.

<?php
   $client = new SoapClient("https://example.com/TESTApi_v1_1.wsdl.php");
   $auth_id = $client->authenticate_get('username', 'password');
   $client = new SoapClient("https://example.com/TESTApi_v1_1.wsdl.php", array("login" => $auth_id ));
 ?>

When I try to call any other methods I am just getting an error returned "HTTP Basic Authorization header required".

I have also tried:

Uri uri = new Uri(url);
            ICredentials credentials = netCredential.GetCredential(uri, "Basic login:" + auth_id);
        client.Credentials = credentials;
            client.PreAuthenticate = true;

I have also been trying:

public class MyHeader : SoapHeader
{
    public string login;
}

[WebService(Namespace = "https://example.com/TESTApi_v1_1.wsdl.php")]
public class exampleTestService : ExampleService
{
    public MyHeader myOutHeader;

    [WebMethod]
    [SoapHeader("login", Direction = SoapHeaderDirection.InOut)]
    public MyHeader MyOutHeaderMethod()
    {
        var client = new ExampleService();
        string auth_id = client.authenticate_get("www.testexample.com", "e5d30c56d600a7e6f3cef05d8c0a1991");
        // Return the client's authenticated name.
        MyHeader outHeader = new MyHeader();
        outHeader.login = auth_id;
        return outHeader;
    }
}

I am sure I am missing something simple.

Thank you in advance for any help.

回答1:

I have got it working. In case anyone else can find my answer helpful:

 public partial class TheWebServiceSubClass : ExampleService
{
    protected override WebRequest GetWebRequest(Uri uri)
    {
        HttpWebRequest webRequest = (HttpWebRequest)base.GetWebRequest(uri);
        ExampleService client = new ExampleService();
        string auth_id = client.authenticate_get("www.testexample.com", "e5d30c56d600a7456846164");
        string credentials =
            Convert.ToBase64String(Encoding.ASCII.GetBytes("www.testexample.com:e5d30c56d600a7456846164"));
        string credentials1 = Convert.ToBase64String(Encoding.ASCII.GetBytes(auth_id+ ":"));
        webRequest.Headers["Authorization"] = "Basic " + credentials1;
        return webRequest;
    }
}