Skip to main content
 首页 » 编程设计

c#之用 .net2.0 和 .net4.0 编写的 Web 服务客户端之间的区别

2024年01月02日37jpfss

我在通过 SSL 使用 java 网络服务时遇到问题。 我有两种方法,一种使用 .net4.0,另一种使用 .net2.0。 不幸的是,.net4.0 方法不起作用。但是,早期版本 (2.0) 工作正常:

class Program 
{ 
    static void Main(string[] args) 
    { 
        try 
        { 
            Srv.Service client = new Srv.Service (); 
            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); 
            store.Open(OpenFlags.ReadOnly); 
            string findValue = "IssuerName"; 
            X509Certificate2Collection certsCollection = store.Certificates.Find(X509FindType.FindByIssuerName, findValue, false); 
 
            X509Certificate2 cert; 
            if (certsCollection.Count > 0) 
            { 
                cert = certsCollection[0]; 
                client.ClientCertificates.Add(cert); // Only in .net 2.0 
            } 
 
            client.MethodA(); 
 
        } 
        catch (Exception e) 
        { 
            string msg = e.Message; 
        } 
    } 
} 

之后我在 .net4.0 客户端中做了类似的事情(抛出“无法使用权​​限 {server_name} 为 SSL/TLS 建立安全通道”异常):

class Program 
{ 
    static void Main(string[] args) 
    { 
        try 
        { 
            Srv.ServiceClient srv = new Srv.ServiceClient(); 
            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); 
            store.Open(OpenFlags.ReadOnly); 
            string findValue = "IssuerName"; 
            X509Certificate2Collection certsCollection = store.Certificates.Find(X509FindType.FindByIssuerName, findValue, false); 
 
            X509Certificate2 cert; 
            if (certsCollection.Count > 0) 
            { 
                cert = certsCollection[0]; 
                srv.ClientCredentials.ClientCertificate.Certificate = new X509Certificate2(); 
                srv.ClientCredentials.ClientCertificate.Certificate = cert; 
            } 
 
            client.MethodA(); 
        } 
        catch (Exception e) 
        { 
            string msg = e.Message; 
        } 
    } 
} 

为什么几乎相同的代码在 2.0 中运行并在 4.0 中抛出异常? 或者也许我在第二个例子中做错了? 覆盖 ServicePointManager.ServerCertificateValidationCallback 没有帮助...

为什么我不能像在 2.0 框架中那样在 4.0 中通过 Add 方法添加用户证书?

编辑: 我没有使用 IIS。我正在使用托管在 JBoss 上的网络服务。

在第二个例子中我得到以下异常:

Could not establish secure channel for SSL/TLS with authority {server_name}

请您参考如下方法:

我遇到了同样的问题。我可以使用 soapUI 调用 Web 服务: 我的解决方案 - 使用“添加服务引用”对话框(高级设置 -> 添加 Web 引用)创建 Web 引用。 请参阅:Web Reference vs. Service Reference和 Difference between web reference and service reference?