Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Finance | Project Operations, Human Resources, ...
Answered

Can't connect to WCF service

(0) ShareShare
ReportReport
Posted on by 130

Hi,


I am trying to connect to an existing WCF service. I am getting the following exception when trying to call wcf service. ProtectionLevel is EncryptAndSign for all methods.


System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.InvalidOperationException: The request message must be protected. This is required by an operation of the contract ('IService','http://tempuri.org/'). The protection must be provided by the binding ('WSHttpBinding','http://tempuri.org/').
   at System.ServiceModel.Dispatcher.SecurityValidationBehavior.ContractProtectionRequirementsRule.ValidateBindingProtectionCapability(Binding binding, ContractDescription contract, ProtectionLevel request, ProtectionLevel response)
   at System.ServiceModel.Dispatcher.SecurityValidationBehavior.ValidateNoSecurityBinding(Binding binding, ContractDescription contract)
   at System.ServiceModel.Dispatcher.SecurityValidationBehavior.ValidateBinding(Binding binding, ContractDescription contract, SecurityBindingElement& securityBindingElement)
   at System.ServiceModel.Dispatcher.SecurityValidationBehavior.System.ServiceModel.Description.IEndpointBehavior.Validate(ServiceEndpoint serviceEndpoint)
   at System.ServiceModel.Description.ServiceEndpoint.Validate(Boolean runOperationValidators, Boolean isForService)
   at System.ServiceModel.Channels.ServiceChannelFactory.BuildChannelFactory(ServiceEndpoint serviceEndpoint, Boolean useActiveAutoClose)
   at System.ServiceModel.ChannelFactory.CreateFactory()
   at System.ServiceModel.ChannelFactory.OnOpening()
   at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
   at System.ServiceModel.ChannelFactory.EnsureOpened()
   at System.ServiceModel.ChannelFactory`1.CreateChannel(EndpointAddress address, Uri via)
   at System.ServiceModel.ChannelFactory`1.CreateChannel()
   at System.ServiceModel.ClientBase`1.CreateChannel()
   at System.ServiceModel.ClientBase`1.CreateChannelInternal()
   at System.ServiceModel.ClientBase`1.get_Channel()
   at ExternalService.Client.Create()
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
   at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at Microsoft.Dynamics.AX.ManagedInterop.ClrBridgeImpl.InvokeClrInstanceMethod(ClrBridgeImpl* , ObjectWrapper* objectWrapper, Char* pszMethodName, Int32 argsLength, ObjectWrapper** arguments, Boolean* argsAreByRef, Boolean* isException)

Example

static void Job1(Args _args)
{
    #define.Type_ServiceClient('ExternalService.Client')

    ExternalService.Client serviceClient;

    System.Exception exception;
    System.Type type;
    ;

    try
    {
        type = CLRInterop::getType(#Type_ServiceClient);

        serviceClient = AifUtil::createServiceClient(type);
        
        serviceClient.Create();
    }
    catch(Exception::CLRError)
    {
        exception = CLRInterop::getLastException();

        while(exception)
        {
            info(CLRInterop::getAnyTypeForObject(exception.ToString()));
            exception = exception.get_InnerException();
        }
    }
}

Can someone help to resolve the issue.

Thanks in advance

  • Janos Kovacs Profile Picture
    130 on at
    RE: Can't connect to WCF service

    I missed it, I added the reference System.ServiceModel.Security.dll. However, I still don't have the enum value for System.ServiceModel.Security.X509CertificateValidationMode::None.

    Image.X509

    I found what I was looking for the missing DLL is System.IdentityModel.dll.

    Image2.X509

    Working code example

    static void Job1(Args _args)
    {
        #define.Type_ServiceClient('ExternalService.Client')
    
        ExternalService.Client                                                  serviceClient;
        System.ServiceModel.Description.ClientCredentials                       clientCredentials;
        System.ServiceModel.Security.X509CertificateRecipientClientCredential   X509CertificateRecipientClientCredential;
        System.ServiceModel.Security.X509ServiceCertificateAuthentication       X509ServiceCertificateAuthentication;
        System.Exception                                                        exception;
        System.Type                                                             type;
        ;
    
        try
        {
            type = CLRInterop::getType(#Type_ServiceClient);
    
            serviceClient = AifUtil::createServiceClient(type);
             
            clientCredentials = serviceClient.get_ClientCredentials();
                  
            X509CertificateRecipientClientCredential = clientCredentials.get_ServiceCertificate();
            X509ServiceCertificateAuthentication = X509CertificateRecipientClientCredential.get_Authentication();
            X509ServiceCertificateAuthentication.set_CertificateValidationMode(System.ServiceModel.Security.X509CertificateValidationMode::None);
    
            serviceClient.Create();
        }
        catch(Exception::CLRError)
        {
            exception = CLRInterop::getLastException();
    
            while(exception)
            {
                info(CLRInterop::getAnyTypeForObject(exception.ToString()));
                exception = exception.get_InnerException();
            }
        }
    }

    Thank you goshoom  for your help.

  • Martin Dráb Profile Picture
    233,043 Most Valuable Professional on at
    RE: Can't connect to WCF service

    How are you trying to access the enum from X++? Is there a reference to System.ServiceModel.Security.dll?

  • Janos Kovacs Profile Picture
    130 on at
    RE: Can't connect to WCF service

    I tried but it doesn't work. I'm probably doing something wrong. 

    	
    		
    			
    				
    					
    				
    			
    		
    	
    

  • Verified answer
    Martin Dráb Profile Picture
    233,043 Most Valuable Professional on at
    RE: Can't connect to WCF service

    Is there any reason why you must change configuration in code? The usuual approach is doing it in the configuration file. See <authentication> of <serviceCertificate> Element.

  • Janos Kovacs Profile Picture
    130 on at
    RE: Can't connect to WCF service

    I just added the Add Service Reference to the C# project. I did not configure anything extra.

    However, I found a solution, but only on the C# side. I cannot access the enum value to X509CertificateValidationMode directly via .NET Interop in Microsft Dynamics AX 2012 and I don't know why. When attempting to correctly decompile the DLL from the location (C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.ServiceModel.Security.dll) used by AX, I can see the existing enum value but AX does not.

    // System.ServiceModel.Security.X509CertificateValidationMode
    using System.Runtime.CompilerServices;
    
    /// An enumeration that lists the ways of validating a certificate.
    [TypeForwardedFrom("System.ServiceModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
    public enum X509CertificateValidationMode
    {
    	/// No validation of the certificate is done.
    	None,
    	/// The certificate is valid if it is in the trusted people store.
    	PeerTrust,
    	/// The certificate is valid if the chain builds to a certification authority in the trusted root store.
    	ChainTrust,
    	/// The certificate is valid if it is in the trusted people store, or if the chain builds to a certification authority in the trusted root store.
    	PeerOrChainTrust,
    	/// The user must plug in a custom  to validate the certificate.
    	Custom
    }
    

    Working piece of code in C#

    using System;
    using System.Security.Cryptography.X509Certificates;
    using System.ServiceModel;
    using System.ServiceModel.Security;
    
    namespace TestClass
    {
        class Program
        {
            static void Main(string[] args)
            {
                try
                {
                    ExternalService.Client client = new ExternalService.Client("WSHttpBinding_IService1");
                    client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
                    client.Create();
                }
                catch (Exception e) 
                {
                    Console.WriteLine("{0} Second exception caught.", e);
                }
            }
        }
    }
    

    My question is how to rewrite this code snippet and define endpointConfigurationName in x ?

  • Martin Dráb Profile Picture
    233,043 Most Valuable Professional on at
    RE: Can't connect to WCF service

    It seems to be question primarily about WCF rather than AX, therefore this likely isn't the best forum.

    If you want to try it here anyway, please tell us more about how you've configured security on the service consumer side.

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Understanding Microsoft Agents - Introductory Session

Confused about how agents work across the Microsoft ecosystem? Register today!

Jonas ”Jones” Melgaard – Community Spotlight

We are honored to recognize Jonas "Jones" Melgaard as our April 2025…

Kudos to the March Top 10 Community Stars!

Thanks for all your good work in the Community!

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 294,424 Super User 2025 Season 1

#2
Martin Dráb Profile Picture

Martin Dráb 233,043 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,158 Moderator

Leaderboard

Product updates

Dynamics 365 release plans