簡體   English   中英

將Web服務配置轉換為代碼

[英]Convert web service configuration to code

我在控制台應用程序中有一個SOAP服務客戶端,我需要將服務客戶端移動到sharepoint 2010.我不想做配置文件部署和其他與sharepoint相關的東西,所以我決定硬編碼綁定信息,唯一可配置的選項是URL。 但是我在這方面遇到了一些麻煩。 我有一個配置:

    <system.serviceModel>
<bindings>
  <customBinding>
    <binding name="SI_PMProjectMaintain_SOUTBinding">
      <textMessageEncoding maxReadPoolSize="64" maxWritePoolSize="16"
        messageVersion="Soap11" writeEncoding="utf-8">
        <readerQuotas maxDepth="10000000" maxStringContentLength="10000000"
          maxArrayLength="67108864" maxBytesPerRead="65536" maxNameTableCharCount="100000" />
      </textMessageEncoding>
      <httpTransport authenticationScheme="Basic" bypassProxyOnLocal="false"
        hostNameComparisonMode="StrongWildcard" keepAliveEnabled="false"
        proxyAuthenticationScheme="Basic" realm="XISOAPApps" useDefaultWebProxy="true" />
    </binding>
  </customBinding>
</bindings>
<client>
  <endpoint address="http://url/XISOAPAdapter/MessageServlet?senderParty=&amp;senderService=Param1&amp;receiverParty=&amp;receiverService=&amp;interface=interface&amp;interfaceNamespace=url"
    binding="customBinding" bindingConfiguration="SI_PMProjectMaintain_SOUTBinding"
    contract="PmProjectMaintain.SI_PMProjectMaintain_SOUT" name="HTTP_Port" />
</client>

另外,我有一個代碼:

    var service = new ServiceClient();
    service.ClientCredentials.Windows.ClientCredential = new NetworkCredential("user", "password");
    service.ClientCredentials.UserName.UserName = "user";
    service.ClientCredentials.UserName.Password = "password";

    var resp = service.Operation();
    Console.WriteLine(resp.Response);

它按預期工作。 現在我想擺脫xml配置並完全將其移動到代碼:

public class CustomHttpTransportBinding : CustomBinding
{
    public CustomHttpTransportBinding()
    {
    }

    public override BindingElementCollection CreateBindingElements()
    {
        var result = new BindingElementCollection();
        result.Add(new TextMessageEncodingBindingElement
        {
            MaxReadPoolSize = 64,
            MaxWritePoolSize = 16,
            MessageVersion = MessageVersion.Soap11,
            WriteEncoding = Encoding.UTF8,

            //ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas
            //{
            //    MaxDepth = 10000000,
            //    MaxStringContentLength = 10000000,
            //    MaxArrayLength = 67108864,
            //    MaxBytesPerRead = 65536,
            //    MaxNameTableCharCount = 100000
            //}
        });

        result.Add(new HttpTransportBindingElement
        {
            AuthenticationScheme = AuthenticationSchemes.Basic,
            BypassProxyOnLocal = false,
            HostNameComparisonMode = System.ServiceModel.HostNameComparisonMode.StrongWildcard,
            KeepAliveEnabled = false,
            ProxyAuthenticationScheme = AuthenticationSchemes.Basic,
            Realm = "XISOAPApps",
            UseDefaultWebProxy = true
        });

        return result;
    }
}

我這樣使用它:

    var service = new ServiceClient(new CustomHttpTransportBinding(), new EndpointAddress(url));
    service.ClientCredentials.Windows.ClientCredential = new NetworkCredential("user", "password");
    service.ClientCredentials.UserName.UserName = "user";
    service.ClientCredentials.UserName.Password = "password";

    var resp = service.Operation();
    Console.WriteLine(resp.Response);

它到達服務器,但拋出異常(“服務器錯誤”),所以我認為我的配置有問題。 我也無法指定讀者配額。 我已經嘗試從字符串加載配置 ,但它不適合我,同樣的錯誤。 Confi似乎我無法將自定義綁定從XML轉換為.net 3.5中的代碼。 有人可以查看我的代碼並確認嗎? 是否有其他方法可以在代碼中使用自定義綁定的服務客戶端?

我還沒有找到一種方法將配置從app.config移動到自定義綁定的代碼,它對basicHttpBinding有效,但不適用於customBinding。

我最終使用自定義chanell工廠從文件加載動態配置。

public class CustomChannelFactory<T> : ChannelFactory<T>
{
    private readonly string _configurationPath;

    public CustomChannelFactory(string configurationPath) : base(typeof(T))
    {
        _configurationPath = configurationPath;
        base.InitializeEndpoint((string)null, null);
    }

    protected override ServiceEndpoint CreateDescription()
    {
        ServiceEndpoint serviceEndpoint = base.CreateDescription();

        ExeConfigurationFileMap executionFileMap = new ExeConfigurationFileMap();
        executionFileMap.ExeConfigFilename = _configurationPath;

        System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(executionFileMap, ConfigurationUserLevel.None);
        ServiceModelSectionGroup serviceModeGroup = ServiceModelSectionGroup.GetSectionGroup(config);

        ChannelEndpointElement selectedEndpoint = null;
        foreach (ChannelEndpointElement endpoint in serviceModeGroup.Client.Endpoints)
        {
            if (endpoint.Contract == serviceEndpoint.Contract.ConfigurationName)
            {
                selectedEndpoint = endpoint;
                break;
            }
        }

        if (selectedEndpoint != null)
        {
            if (serviceEndpoint.Binding == null)
            {
                serviceEndpoint.Binding = CreateBinding(selectedEndpoint.Binding, serviceModeGroup);
            }

            if (serviceEndpoint.Address == null)
            {
                serviceEndpoint.Address = new EndpointAddress(selectedEndpoint.Address, GetIdentity(selectedEndpoint.Identity), selectedEndpoint.Headers.Headers);
            }

            if (serviceEndpoint.Behaviors.Count == 0 && !String.IsNullOrEmpty(selectedEndpoint.BehaviorConfiguration))
            {
                AddBehaviors(selectedEndpoint.BehaviorConfiguration, serviceEndpoint, serviceModeGroup);
            }

            serviceEndpoint.Name = selectedEndpoint.Contract;
        }

        return serviceEndpoint;
    }

    private Binding CreateBinding(string bindingName, ServiceModelSectionGroup group)
    {
        BindingCollectionElement bindingElementCollection = group.Bindings[bindingName];
        if (bindingElementCollection.ConfiguredBindings.Count > 0)
        {
            IBindingConfigurationElement be = bindingElementCollection.ConfiguredBindings[0];

            Binding binding = GetBinding(be);
            if (be != null)
            {
                be.ApplyConfiguration(binding);
            }

            return binding;
        }

        return null;
    }

    private void AddBehaviors(string behaviorConfiguration, ServiceEndpoint serviceEndpoint, ServiceModelSectionGroup group)
    {
        EndpointBehaviorElement behaviorElement = group.Behaviors.EndpointBehaviors[behaviorConfiguration];
        for (int i = 0; i < behaviorElement.Count; i++)
        {
            BehaviorExtensionElement behaviorExtension = behaviorElement[i];
            object extension = behaviorExtension.GetType().InvokeMember("CreateBehavior",
            BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance,
            null, behaviorExtension, null);
            if (extension != null)
            {
                serviceEndpoint.Behaviors.Add((IEndpointBehavior)extension);
            }
        }
    }

    private EndpointIdentity GetIdentity(IdentityElement element)
    {
        EndpointIdentity identity = null;
        PropertyInformationCollection properties = element.ElementInformation.Properties;
        if (properties["userPrincipalName"].ValueOrigin != PropertyValueOrigin.Default)
        {
            return EndpointIdentity.CreateUpnIdentity(element.UserPrincipalName.Value);
        }
        if (properties["servicePrincipalName"].ValueOrigin != PropertyValueOrigin.Default)
        {
            return EndpointIdentity.CreateSpnIdentity(element.ServicePrincipalName.Value);
        }
        if (properties["dns"].ValueOrigin != PropertyValueOrigin.Default)
        {
            return EndpointIdentity.CreateDnsIdentity(element.Dns.Value);
        }
        if (properties["rsa"].ValueOrigin != PropertyValueOrigin.Default)
        {
            return EndpointIdentity.CreateRsaIdentity(element.Rsa.Value);
        }
        if (properties["certificate"].ValueOrigin != PropertyValueOrigin.Default)
        {
            X509Certificate2Collection supportingCertificates = new X509Certificate2Collection();
            supportingCertificates.Import(Convert.FromBase64String(element.Certificate.EncodedValue));
            if (supportingCertificates.Count == 0)
            {
                throw new InvalidOperationException("UnableToLoadCertificateIdentity");
            }
            X509Certificate2 primaryCertificate = supportingCertificates[0];
            supportingCertificates.RemoveAt(0);
            return EndpointIdentity.CreateX509CertificateIdentity(primaryCertificate, supportingCertificates);
        }

        return identity;
    }

    private Binding GetBinding(IBindingConfigurationElement configurationElement)
    {
        if (configurationElement is CustomBindingElement)
            return new CustomBinding();
        else if (configurationElement is BasicHttpBindingElement)
            return new BasicHttpBinding();
        else if (configurationElement is NetMsmqBindingElement)
            return new NetMsmqBinding();
        else if (configurationElement is NetNamedPipeBindingElement)
            return new NetNamedPipeBinding();
        else if (configurationElement is NetPeerTcpBindingElement)
            return new NetPeerTcpBinding();
        else if (configurationElement is NetTcpBindingElement)
            return new NetTcpBinding();
        else if (configurationElement is WSDualHttpBindingElement)
            return new WSDualHttpBinding();
        else if (configurationElement is WSHttpBindingElement)
            return new WSHttpBinding();
        else if (configurationElement is WSFederationHttpBindingElement)
            return new WSFederationHttpBinding();

        return null;
    }
}

有用的鏈接:

發現boades回復中引用的代碼存在問題,因為如果你在basicHttpbinding下有混合傳輸綁定( https / http ),你可能會得到類似/反向的異常:

提供的URI方案“https”無效; 預計'http'。 參數名稱:via

我還希望您也會發生意外授權,因為代碼將使用web.config列出的第一個bindingConfiguration而不是名稱。

違規行沒有按名稱進行綁定,而只取第一個(!)

IBindingConfigurationElement be = bindingElementCollection.ConfiguredBindings [0];

這可以通過更新CreateBinding方法和CreateDescription的調用來糾正,如下所示:

protected override ServiceEndpoint CreateDescription()
{
    ServiceEndpoint description = base.CreateDescription();
    if (CustomisedChannelFactory<TChannel>.ConfigurationPath == null || !System.IO.File.Exists(CustomisedChannelFactory<TChannel>.ConfigurationPath))
        return base.CreateDescription();
    ServiceModelSectionGroup sectionGroup = ServiceModelSectionGroup.GetSectionGroup(ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap()
    {
        ExeConfigFilename = CustomisedChannelFactory<TChannel>.ConfigurationPath
    }, ConfigurationUserLevel.None));
    ChannelEndpointElement channelEndpointElement1 = (ChannelEndpointElement)null;
    foreach (ChannelEndpointElement channelEndpointElement2 in (ConfigurationElementCollection)sectionGroup.Client.Endpoints)
    {
        if (channelEndpointElement2.Contract == description.Contract.ConfigurationName)
        {
            channelEndpointElement1 = channelEndpointElement2;
            break;
        }
    }
    if (channelEndpointElement1 != null)
    {
        if (description.Binding == null)
            description.Binding = this.CreateBinding(channelEndpointElement1.Binding, channelEndpointElement1.BindingConfiguration, sectionGroup);
        if (description.Address == (EndpointAddress)null)
            description.Address = new EndpointAddress(channelEndpointElement1.Address, this.GetIdentity(channelEndpointElement1.Identity), channelEndpointElement1.Headers.Headers);
        if (description.Behaviors.Count == 0 && !string.IsNullOrEmpty(channelEndpointElement1.BehaviorConfiguration))
            this.AddBehaviors(channelEndpointElement1.BehaviorConfiguration, description, sectionGroup);
        description.Name = channelEndpointElement1.Contract;
    }
    return description;
}

private Binding CreateBinding(string bindingName, string bindingConfigurationName, ServiceModelSectionGroup group)
{
    BindingCollectionElement collectionElement = group.Bindings[bindingName];
    if (collectionElement.ConfiguredBindings.Count <= 0)
        return (Binding)null;

    IBindingConfigurationElement configurationElement = null;
    foreach (IBindingConfigurationElement bce in collectionElement.ConfiguredBindings)
    {
        if (bce.Name.Equals(bindingConfigurationName))
        {
            configurationElement = bce;
            break;
        }
    }
    if (configurationElement == null) throw new Exception("BindingConfiguration " + bindingConfigurationName + " not found under binding " + bindingName);

    Binding binding = this.GetBinding(configurationElement);
    if (configurationElement != null)
        configurationElement.ApplyConfiguration(binding);
    return binding;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM