CRM Dynamics调用WCF服务错误

本文关键字:服务 错误 WCF 调用 Dynamics CRM | 更新日期: 2023-09-27 18:24:01

嗨,我有一个CRM 2013插件,它调用WCF服务,该服务失败并出现以下错误:

'通信对象,System.ServiceModel.ChannelFactory `1[ISupplyClaimsService],不能为在打开状态下修改’,

我有时也会发现,当调用该服务时,插件注册工具会崩溃。是否可以从插件调用WCF服务?我在网上看到了一些帖子,但没有具体的工作解决方案,甚至在CRM SDK中也没有。我的CRM是内部部署2013,插件是在Sandbox隔离(NONE)之外注册的,WCF服务使用命名域而不是IP地址,它通过HTTP协议运行,请参阅下面的代码。我已经满足了关于插件和外部系统的所有要求,但仍然没有运气。我还在控制台应用程序中测试了该服务,SOAP UI运行良好,只是在插件中我遇到了问题。

public void Execute(IServiceProvider serviceProvider)
    {
        ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
        IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
        if (context == null)
        {
            throw new ArgumentNullException("loaclContext");
        }
        if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
        {
            Entity supplyClaimsEntity = (Entity)context.InputParameters["Target"];
            if (supplyClaimsEntity.LogicalName != "new_supplierclaimsupdate")
            {
                return;
            }
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.InitiatingUserId);
            string entityBeginUpload = "Start Upload";
            try
            {
                BasicHttpBinding myBinding = new BasicHttpBinding();
                myBinding.Name = "BasicHttpBinding_ISupplyClaimsService";
                myBinding.Security.Mode = BasicHttpSecurityMode.None;
                myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
                myBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
                myBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
                EndpointAddress endPointAddress = new EndpointAddress(@"http://wmvapps01.tarsus.co.za/SupplyClaimsService.svc");
                ChannelFactory<ISupplyClaimsService> factory = new ChannelFactory<ISupplyClaimsService>(myBinding, endPointAddress);
                ISupplyClaimsService channel = factory.CreateChannel();
                channel.StartApplication();
                factory.Close();

            }

CRM Dynamics调用WCF服务错误

我有一个具有Rest methodWCF Rest WebService。WebService代码:

public interface ICRMRestWebService
{
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,    
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest,
UriTemplate = "GetLatestContractByContactIdRestMethod")]
LatestMembershipResponse GetLatestContractByContactIdRestMethod(string contactId, AuthenticateRequest authenticateRequest);
}

WCF Rest WebService is:的Web.config

<system.serviceModel>
<services>
  <service name="GRID.CRM.WebServices.CRMRestWebService.CRMRestWebService" behaviorConfiguration="ServiceBehaviour">
    <endpoint address=""  binding="webHttpBinding" contract="GRID.CRM.WebServices.CRMRestWebService.ICRMRestWebService" behaviorConfiguration="web">
    </endpoint>
  </service>
</services>
<bindings />
<client />
<behaviors>
  <serviceBehaviors>
    <behavior name="ServiceBehaviour">
      <serviceMetadata httpGetEnabled="true"/>
      <serviceDebug includeExceptionDetailInFaults="true"/>
    </behavior>
  </serviceBehaviors>
  <endpointBehaviors>
    <behavior name="web">
      <webHttp/>
    </behavior>
  </endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />

我从CRM Plugin调用这个方法,如下所示:

public void Execute(IServiceProvider serviceProvider)
  {
    IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
    IOrganizationServiceFactory serviceFactory;
    IOrganizationService service;
    if (context.Depth > 1)
            return;
    if (context.InputParameters.Contains("Target"))
    {
      //Create Service from Service Factory
     serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
     service = serviceFactory.CreateOrganizationService(context.UserId);
     var javaScriptSerializer = new JavaScriptSerializer();
     javaScriptSerializer.MaxJsonLength = 104857600; //200 MB unicode
            StringBuilder URI = new StringBuilder();
            URI.Append(crmRestWebServiceUrl).Append(webServiceMethod);
            //Logger.Info("GetLatestMembershipFromCRMRestWebService is called with Url: " + URI.ToString());
            var request = (HttpWebRequest)WebRequest.Create(URI.ToString());
            request.Method = "POST";
            request.Accept = "application/json";
            request.ContentType = "application/json; charset=utf-8";
            //Serialize request object as JSON and write to request body
            if (latestMembershipRequest != null)
            {
                var stringBuilder = new StringBuilder();
                javaScriptSerializer.Serialize(latestMembershipRequest, stringBuilder);
                var requestBody = stringBuilder.ToString();
                request.ContentLength = requestBody.Length;
                var streamWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
                streamWriter.Write(requestBody);
                streamWriter.Close();
               // Logger.Info("Request Object that will be sent is: " + stringBuilder.ToString());
            }
           // Logger.Info("Sending Request to CRMRestWebService to get LatestMembership.");
            var response = request.GetResponse();
            //Read JSON response stream and deserialize
            var streamReader = new System.IO.StreamReader(response.GetResponseStream());
            var responseContent = streamReader.ReadToEnd().Trim();
            LatestMembershipResponse latestMembershipResponse = javaScriptSerializer.Deserialize<LatestMembershipResponse>(responseContent);
           // Logger.Info("Latest Membership Reveived is: " + responseContent.ToString() + " has been deserialized Successfully.");
            return latestMembershipResponse;
}