在 C# 中预验证 Web 服务请求 [英] Pre authenticate web service request in C#
问题描述
我在 C# 中调用 Web 服务请求时遇到问题.
I'm having a problem with calling a web service request in C#.
服务和请求在 Soap UI 中运行良好,启用了预先验证"选项(文件、首选项、HTTP 设置).如果未启用此设置,服务将返回Java.Lang.NullPointerException".
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'.
我遇到的问题是我不知道如何在 C# 上下文中启用此设置.
The problem I'm having is that I do not know how to enable this setting in a C# context.
我有一个 .NET 3.5 类库,其中包含对特定服务的所谓服务引用.这是一个简单的代码片段;
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);
}
第一次回复后更新.
CatalogService.CatalogChangeClient 类似乎实现了 WCF 抽象类
The CatalogService.CatalogChangeClient class seems to implement the WCF abstract class
System.ServiceModel.ClientBase<TChannel>
结束更新
谁能帮我设置这个属性?
Could anyone help me set this property?
推荐答案
您可以尝试覆盖生成的客户端存根中的 GetWebRequest
方法.我用过一次,这解决了我的问题.
You could try and override the GetWebRequest
method from your generated client stub. I have used this once and that solved my problem.
查看以下网址:
向下滚动一点.
这是链接中的代码:
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;
}
这篇关于在 C# 中预验证 Web 服务请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!