【问题标题】:How do I set the correct content type in a WCF binding without using app.config?如何在不使用 app.config 的情况下在 WCF 绑定中设置正确的内容类型?
【发布时间】:2011-11-23 08:13:22
【问题描述】:

我从测试控制台应用程序创建了对 CRM 2011 Organization.svc 的服务引用。 使用 app.config 中生成的绑定可以完美运行。(Microsoft here 托管的服务示例。)

现在需要将其移动到我们的“真实”应用程序中并托管在将部署到 GAC 的 DLL 中。在遵循应用程序的约定时,绑定需要由代码生成

我已经开始尝试使用我们用于其他 WCF 服务的绑定:

BasicHttpBinding binding = new BasicHttpBinding();
binding.SendTimeout = TimeSpan.FromMinutes(1);
binding.OpenTimeout = TimeSpan.FromMinutes(1);
binding.CloseTimeout = TimeSpan.FromMinutes(1);
binding.ReceiveTimeout = TimeSpan.FromMinutes(10);
binding.AllowCookies = true;
binding.BypassProxyOnLocal = false;
binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
binding.MessageEncoding = WSMessageEncoding.Text;
binding.TextEncoding = System.Text.Encoding.UTF8;
binding.TransferMode = TransferMode.Buffered;
binding.UseDefaultWebProxy = true;
binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;

不幸的是,在调用 WCF 服务时(使用带有 OrganizationRequest 的 Execute 方法),出现此错误:

System.ServiceModel.ProtocolException: 内容类型 text/xml;服务 http://server:5555/xrmservices/2011/organization.svc 不支持 charset=utf-8。客户端和服务绑定可能不匹配。

我不确定绑定的具体问题是什么,但到目前为止,我尝试将其转换为代码的尝试都失败了,并出现了同样的错误。这是 app.config 中定义的工作绑定:

<bindings>
    <customBinding>
        <binding name="CustomBinding_IOrganizationService">
            <security defaultAlgorithmSuite="Default" authenticationMode="SspiNegotiated"
                requireDerivedKeys="true" securityHeaderLayout="Strict" includeTimestamp="true"
                keyEntropyMode="CombinedEntropy" messageProtectionOrder="SignBeforeEncryptAndEncryptSignature"
                messageSecurityVersion="WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10"
                requireSecurityContextCancellation="true" requireSignatureConfirmation="false">
                <localClientSettings cacheCookies="true" detectReplays="true"
                    replayCacheSize="900000" maxClockSkew="00:05:00" maxCookieCachingTime="Infinite"
                    replayWindow="00:05:00" sessionKeyRenewalInterval="10:00:00"
                    sessionKeyRolloverInterval="00:05:00" reconnectTransportOnFailure="true"
                    timestampValidityDuration="00:05:00" cookieRenewalThresholdPercentage="60" />
                <localServiceSettings detectReplays="true" issuedCookieLifetime="10:00:00"
                    maxStatefulNegotiations="128" replayCacheSize="900000" maxClockSkew="00:05:00"
                    negotiationTimeout="00:01:00" replayWindow="00:05:00" inactivityTimeout="00:02:00"
                    sessionKeyRenewalInterval="15:00:00" sessionKeyRolloverInterval="00:05:00"
                    reconnectTransportOnFailure="true" maxPendingSessions="128"
                    maxCachedCookies="1000" timestampValidityDuration="00:05:00" />
                <secureConversationBootstrap />
            </security>
            <textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16"
                messageVersion="Default" writeEncoding="utf-8">
                <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
                    maxBytesPerRead="4096" maxNameTableCharCount="16384" />
            </textMessageEncoding>
            <httpTransport manualAddressing="false" maxBufferPoolSize="524288"
                maxReceivedMessageSize="65536" allowCookies="false" authenticationScheme="Anonymous"
                bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
                keepAliveEnabled="true" maxBufferSize="65536" proxyAuthenticationScheme="Anonymous"
                realm="" transferMode="Buffered" unsafeConnectionNtlmAuthentication="false"
                useDefaultWebProxy="true" />
        </binding>
    </customBinding>
</bindings>

有谁知道如何在代码中设置正确的绑定和/或从 XML 读取绑定?

【问题讨论】:

    标签: wcf wcf-binding dynamics-crm-2011


    【解决方案1】:

    我只是有同样的任务要解决。这对我有用(对于http)。

    var security = SecurityBindingElement.CreateSspiNegotiationBindingElement();
    security.DefaultAlgorithmSuite = SecurityAlgorithmSuite.Default;
    security.SecurityHeaderLayout = SecurityHeaderLayout.Strict;
    security.IncludeTimestamp = true;
    security.KeyEntropyMode = SecurityKeyEntropyMode.CombinedEntropy;
    security.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature;
    security.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
    
    security.LocalClientSettings.CacheCookies = true;
    security.LocalClientSettings.DetectReplays = true;
    security.LocalClientSettings.ReplayCacheSize = 900000;
    security.LocalClientSettings.MaxClockSkew = new TimeSpan(0, 5, 0);
    security.LocalClientSettings.MaxCookieCachingTime = new TimeSpan(23, 0, 0, 0);
    security.LocalClientSettings.ReplayWindow = new TimeSpan(0, 5, 0);
    security.LocalClientSettings.SessionKeyRenewalInterval = new TimeSpan(15, 0, 0);
    security.LocalClientSettings.SessionKeyRolloverInterval = new TimeSpan(0, 5, 0);
    security.LocalClientSettings.ReconnectTransportOnFailure = true;
    security.LocalClientSettings.TimestampValidityDuration = new TimeSpan(0, 5, 0);
    security.LocalClientSettings.CookieRenewalThresholdPercentage = 60;
    
    security.LocalServiceSettings.DetectReplays = true;
    security.LocalServiceSettings.IssuedCookieLifetime = new TimeSpan(10, 0, 0);
    security.LocalServiceSettings.MaxStatefulNegotiations = 128;
    security.LocalServiceSettings.ReplayCacheSize = 900000;
    security.LocalServiceSettings.MaxClockSkew = new TimeSpan(0, 5, 0);
    security.LocalServiceSettings.NegotiationTimeout = new TimeSpan(0, 1, 0);
    security.LocalServiceSettings.ReplayWindow = new TimeSpan(0, 5, 0);
    security.LocalServiceSettings.InactivityTimeout = new TimeSpan(0, 2, 0);
    security.LocalServiceSettings.SessionKeyRenewalInterval = new TimeSpan(15, 0, 0);
    security.LocalServiceSettings.SessionKeyRolloverInterval = new TimeSpan(0, 5, 0);
    security.LocalServiceSettings.ReconnectTransportOnFailure = true;
    security.LocalServiceSettings.MaxPendingSessions = 128;
    security.LocalServiceSettings.MaxCachedCookies = 1000;
    security.LocalServiceSettings.TimestampValidityDuration = new TimeSpan(0, 5, 0);
    
    var textEncoding = new TextMessageEncodingBindingElement
    {
       MaxReadPoolSize = 64,
       MaxWritePoolSize = 16,
       MessageVersion = MessageVersion.Default,
       WriteEncoding = System.Text.Encoding.UTF8,
       ReaderQuotas = new XmlDictionaryReaderQuotas
       {
           MaxDepth = 32,
           MaxArrayLength = 16384,
           MaxBytesPerRead = 4096,
           MaxNameTableCharCount = 16384,
           MaxStringContentLength = 8192
       }
    };
    
    var httpTransport = new HttpTransportBindingElement
    {
        ManualAddressing = false,
        MaxBufferSize = 65536,
        MaxReceivedMessageSize = 65536,
        AllowCookies = false,
        AuthenticationScheme = AuthenticationSchemes.Anonymous,
        BypassProxyOnLocal = false,
        DecompressionEnabled = true,
        HostNameComparisonMode = HostNameComparisonMode.StrongWildcard,
        KeepAliveEnabled = true,
        MaxBufferPoolSize = 524288,
        ProxyAuthenticationScheme = AuthenticationSchemes.Anonymous,
        TransferMode = TransferMode.Buffered,
        UnsafeConnectionNtlmAuthentication = false,
        UseDefaultWebProxy = true,
    };
    
    var binding = new CustomBinding(new List<BindingElement> { security, textEncoding, httpTransport });
    var endpoint = new EndpointAddress(_serviceUri);
    
    var service = new OrganizationServiceClient(binding, endpoint);
    

    【讨论】:

      【解决方案2】:

      创建自定义渠道工厂是解决此问题的关键部分。

      Get your WCF client configuration from anywhere 文章对于使用自定义服务客户端从您选择的位置读取 .config 文件非常有帮助。

      Calling WCF Service using Client Channel Factory 中描述了以与 app.config 格式非常相似的方式设置所有值的替代方法,它描述了如何创建自定义绑定。我发现并不是所有的安全属性都可以这样设置(或者至少我找不到它们)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-28
        • 2011-07-08
        • 1970-01-01
        • 2018-08-17
        • 2012-12-05
        • 1970-01-01
        • 2011-04-08
        相关资源
        最近更新 更多