Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在异步操作上启用安全性时,为什么不调用WCF服务_Wcf_Wcf Security - Fatal编程技术网

在异步操作上启用安全性时,为什么不调用WCF服务

在异步操作上启用安全性时,为什么不调用WCF服务,wcf,wcf-security,Wcf,Wcf Security,如果使用X509证书为身份验证启用了安全功能,则不会建立与服务器的连接。当客户端进行异步操作调用时,我发现了这个问题。下面的代码用于同步操作。例如,如果调用是TrainHealth而不是BeginTrainHealth,则代码工作正常。据我所知,安全性与操作是同步还是异步无关。 任何关于为什么这不起作用的帮助都将不胜感激 合同: [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [

如果使用X509证书为身份验证启用了安全功能,则不会建立与服务器的连接。当客户端进行异步操作调用时,我发现了这个问题。下面的代码用于同步操作。例如,如果调用是TrainHealth而不是BeginTrainHealth,则代码工作正常。据我所知,安全性与操作是同步还是异步无关。 任何关于为什么这不起作用的帮助都将不胜感激

合同:

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(Namespace = "http://www.bane.dk/services/fbane/2014/02/20", ConfigurationName = "Alstom.SmartBus.ESBBridge.ExternalIOPlugins.TrainData.TrainDataPort")]
public interface IStudentService
{
    [System.ServiceModel.OperationContractAttribute(IsOneWay = true, AsyncPattern = false, Action = "TrainHealth")]
    [System.ServiceModel.XmlSerializerFormatAttribute()]
    void TrainHealth(int test);

    [System.ServiceModel.OperationContractAttribute(IsOneWay = true, AsyncPattern = true, Action = "TrainHealth")]
    [System.ServiceModel.XmlSerializerFormatAttribute()]
    System.IAsyncResult BeginTrainHealth(int test, System.AsyncCallback callback, object asyncState);

    void EndTrainHealth(System.IAsyncResult result);
}
服务器代码:

class Program
    {
        static void Main(string[] args)
        {
            ServiceHost studentServiceHost = null;
            try
            {
                //Base Address for StudentService
                Uri httpBaseAddress = new Uri("https://10.107.64.33:5060/StudentService");

                //Instantiate ServiceHost
                studentServiceHost = new ServiceHost(typeof(StudentService), httpBaseAddress);

                CustomBinding binding = CreateBinding();
                ServiceEndpoint endpoint_GD = studentServiceHost.AddServiceEndpoint(typeof(IStudentService), binding, httpBaseAddress);

                //Add Endpoint to Host
                studentServiceHost.AddServiceEndpoint(typeof(IStudentService), binding, httpBaseAddress + "mex");

                //Metadata Exchange
                ServiceMetadataBehavior serviceBehavior = new ServiceMetadataBehavior();
                serviceBehavior.HttpsGetEnabled = true;
                studentServiceHost.Description.Behaviors.Add(serviceBehavior);
                var behavior = studentServiceHost.Description.Behaviors.Find<ServiceDebugBehavior>();
                behavior.IncludeExceptionDetailInFaults = true;
                studentServiceHost.Credentials.ClientCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.PeerTrust;
                studentServiceHost.Credentials.ClientCertificate.Authentication.TrustedStoreLocation = StoreLocation.LocalMachine;

                studentServiceHost.Credentials.ServiceCertificate.SetCertificate(System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine, System.Security.Cryptography.X509Certificates.StoreName.My, System.Security.Cryptography.X509Certificates.X509FindType.FindBySubjectName, "10.107.64.33");

                ServiceSecurityAuditBehavior newAudit = new ServiceSecurityAuditBehavior();
                newAudit.AuditLogLocation = AuditLogLocation.Application;
                newAudit.MessageAuthenticationAuditLevel = AuditLevel.SuccessOrFailure;
                newAudit.ServiceAuthorizationAuditLevel = AuditLevel.SuccessOrFailure;
                newAudit.SuppressAuditFailure = false;
                studentServiceHost.Description.Behaviors.Remove<ServiceSecurityAuditBehavior>();
                studentServiceHost.Description.Behaviors.Add(newAudit);

                studentServiceHost.Open();

                Console.WriteLine("Service is live now at : {0}", httpBaseAddress);
                Console.ReadKey();

            }
            catch (Exception ex)
            {
                studentServiceHost = null;
                Console.WriteLine("There is an issue with StudentService" + ex.Message);
                Console.ReadKey();

            }
        }

        public static CustomBinding CreateBinding()
        {
            CustomBinding binding = new CustomBinding();
            binding.Elements.Add(new ReliableSessionBindingElement());
            TransportSecurityBindingElement sec = new TransportSecurityBindingElement();
            binding.Elements.Add(sec);
            binding.Elements.Add(new TextMessageEncodingBindingElement(MessageVersion.Soap11WSAddressing10, Encoding.UTF8));
            binding.Elements.Add(new HttpsTransportBindingElement()
            {
                RequireClientCertificate = true
            });

            return binding;
        }
    }
类程序
{
静态void Main(字符串[]参数)
{
ServiceHost studentServiceHost=null;
尝试
{
//StudentService的基址
Uri httpBaseAddress=新Uri(“https://10.107.64.33:5060/StudentService");
//实例化ServiceHost
studentServiceHost=新服务主机(类型为(StudentService),httpBaseAddress);
CustomBinding=CreateBinding();
ServiceEndpoint endpoint_GD=studentServiceHost.AddServiceEndpoint(typeof(IStudentService),绑定,httpBaseAddress);
//将端点添加到主机
AddServiceEndpoint(typeof(IStudentService),绑定,httpBaseAddress+“mex”);
//元数据交换
ServiceMetadataBehavior serviceBehavior=新ServiceMetadataBehavior();
serviceBehavior.HttpsGetEnabled=true;
studentServiceHost.Description.Behaviors.Add(serviceBehavior);
var behavior=studentServiceHost.Description.Behaviors.Find();
behavior.IncludeExceptionDetailInFaults=true;
studentServiceHost.Credentials.ClientCertificate.Authentication.CertificateValidationMode=System.ServiceModel.Security.X509CertificateValidationMode.PeerTrust;
studentServiceHost.Credentials.ClientCertificate.Authentication.TrustedStoreLocation=StoreLocation.LocalMachine;
studentServiceHost.Credentials.ServiceCertificate.SetCertificate(System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine,System.Security.Cryptography.X509Certificates.X509FindType.FindBySubjectName,“10.107.64.33”);
ServiceSecurityAuditBehavior newAudit=新ServiceSecurityAuditBehavior();
newAudit.AuditLogLocation=AuditLogLocation.Application;
newAudit.MessageAuthenticationAuditLevel=AuditLevel.SuccessOrFailure;
newAudit.ServiceAuthorizationAuditLevel=AuditLevel.SuccessOrFailure;
newAudit.SuppressAuditFailure=false;
studentServiceHost.Description.Behaviors.Remove();
studentServiceHost.Description.Behaviors.Add(newAudit);
studentServiceHost.Open();
WriteLine(“服务现在位于:{0}”,httpBaseAddress)上运行;
Console.ReadKey();
}
捕获(例外情况除外)
{
studentServiceHost=null;
Console.WriteLine(“StudentService有问题”+ex.Message);
Console.ReadKey();
}
}
公共静态CustomBinding CreateBinding()
{
CustomBinding=新的CustomBinding();
添加(新的ReliableSessionBindingElement());
TransportSecurityBindingElement sec=新的TransportSecurityBindingElement();
binding.Elements.Add(秒);
添加(新的TextMessageEncodingBindingElement(MessageVersion.Soap11WSAddressing10,Encoding.UTF8));
binding.Elements.Add(新的HttpsTransportBindingElement()
{
RequireClientCertificate=true
});
返回绑定;
}
}
客户端代码:

 class Program
    {
        static ChannelFactory<IStudentService> runTrainSvcCF = null;

        static IStudentService runTrainSvcProxy;
        static void Main(string[] args)
        {
            StartClient();
        }

        private static void StartClient()
        {
            EndpointAddress endPoint = new EndpointAddress(new Uri("https://10.107.64.33:5060/StudentService"), EndpointIdentity.CreateDnsIdentity("10.107.64.34"));

            CustomBinding binding = CreateBinding();
            runTrainSvcCF = new ChannelFactory<IStudentService>(binding, endPoint);
            System.ServiceModel.Description.ClientCredentials credentials = runTrainSvcCF.Credentials;
            credentials.ClientCertificate.SetCertificate(System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser,
                                                         System.Security.Cryptography.X509Certificates.StoreName.My,
                                                         System.Security.Cryptography.X509Certificates.X509FindType.FindBySubjectName,
                                                         "10.107.64.34");
            ServicePointManager.MaxServicePointIdleTime = 0;
            credentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.PeerTrust;
            ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(ValidateRemoteCertificate);
            runTrainSvcProxy = runTrainSvcCF.CreateChannel();
            try
            {
                runTrainSvcProxy.BeginTrainHealth(88, null, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }

        private static bool ValidateRemoteCertificate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate cert,
                                              System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors policyErrors)
        {
            return true;
        }



        public static CustomBinding CreateBinding()
        {
            CustomBinding binding = new CustomBinding();
            binding.Elements.Add(new ReliableSessionBindingElement());
            binding.Elements.Add(new TransportSecurityBindingElement());
            binding.Elements.Add(new TextMessageEncodingBindingElement(MessageVersion.Soap11WSAddressing10, Encoding.UTF8));
            binding.Elements.Add(new HttpsTransportBindingElement()
            {
                RequireClientCertificate = true
            });

            return binding;
        }
    }
类程序
{
静态ChannelFactory runTrainSvcCF=null;
静态IStudentService runTrainSvcProxy;
静态void Main(字符串[]参数)
{
StartClient();
}
私有静态void StartClient()
{
EndpointAddress endPoint=新的EndpointAddress(新Uri(“https://10.107.64.33:5060/StudentService),EndpointIdentity.createdNsidenty(“10.107.64.34”);
CustomBinding=CreateBinding();
runTrainSvcCF=新的ChannelFactory(绑定,端点);
System.ServiceModel.Description.ClientCredentials credentials=runTrainSvcCF.credentials;
credentials.ClientCertificate.SetCertificate(System.Security.Cryptography.X509Certificates.StoreLocation.CurrentUser,
System.Security.Cryptography.X509Certificates.StoreName.My,
System.Security.Cryptography.X509Certificates.X509FindType.FindBySubjectName,
"10.107.64.34");
ServicePointManager.MaxServicePointIdleTime=0;
credentials.ServiceCertificate.Authentication.CertificateValidationMode=System.ServiceModel.Security.X509CertificateValidationMode.PeerTrust;
ServicePointManager.ServerCertificateValidationCallback+=新系统.Net.Security.RemoteCertificateValidationCallback(ValidateRemoteCertificate);
runTrainSvcProxy=runTrainSvcCF.CreateChannel();
尝试
{
runTrainSvcProxy.BeginTrainHealth(88,null,null);
}
捕获(例外情况除外)
{
控制台写入线(例如消息);
}
}
私有静态bool ValidateRemoteCertificate(对象发送方,System.Security.Cryptography.X509Certificates.X509Certificate证书,
System.Security.Cryptography.X509Certif