开发者

Pre authenticate web service request in C#

I'm having a problem with calling a web service request in C#.

The service and request are working fine in Soap UI with the option 'Authenticate Preemptively' enabled (File, Preferences, HTTP Settings). Without this setting enabled the service returns a 'Java.Lang.NullPointerException'.

The problem I'm having is that I do not know how to enable this setting in a C# context.

I have a .NET 3.5 class library which holds a so called service reference to the specific service. This is a simple code snippet;

try
{
    CatalogService.CatalogChangeClient service = new CatalogService.CatalogChangeClient();开发者_运维技巧
    service.ClientCredentials.UserName.UserName = "fancydress";
    service.ClientCredentials.UserName.Password = "47fda9cb4b51a9e";
    service.ClientCredentials.SupportInteractive = true;

    ProductUpdate[] products = new ProductUpdate[1];
    products[0] = new ProductUpdate();
    products[0].ProductCode = "00001";
    products[0].ProductDescription = "TestProduct";

    string result = service.UpdateProducts(products);
}
catch (Exception exception)
{
    Console.WriteLine(exception.Message);
}

Update after first reply.

The CatalogService.CatalogChangeClient class seems to implement the WCF abstract class

System.ServiceModel.ClientBase<TChannel>

End Update

Could anyone help me set this property?


You could try and override the GetWebRequest method from your generated client stub. I have used this once and that solved my problem.

Look at the following URL:

http://www.eggheadcafe.com/community/wcf/18/10056093/consuming-webservices-and-http-basic-authentication.aspx

Scroll a bit down.

Here's the code from the link:

protected override System.Net.WebRequest GetWebRequest(Uri uri)
{
    HttpWebRequest request;
    request = (HttpWebRequest)base.GetWebRequest(uri);

    if (PreAuthenticate)
    {
        NetworkCredential networkCredentials =
            Credentials.GetCredential(uri, "Basic");

        if (networkCredentials != null)
        {
            byte[] credentialBuffer = new UTF8Encoding().GetBytes(
                networkCredentials.UserName + ":" +
                networkCredentials.Password);
            request.Headers["Authorization"] =
                "Basic " + Convert.ToBase64String(credentialBuffer);
        }
        else
        {
            throw new ApplicationException("No network credentials");
        }
    }
    return request;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜