随笔 - 850  文章 - 37  评论 - 173  阅读 - 287万

Translate this app.config xml to code? (WCF) z

http://stackoverflow.com/questions/730693/translate-this-app-config-xml-to-code-wcf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="MyService"
                 closeTimeout="00:01:00"
                 openTimeout="00:01:00"
                 receiveTimeout="00:10:00"
                 sendTimeout="00:01:00"
                 allowCookies="false"
                 bypassProxyOnLocal="false"
                 hostNameComparisonMode="StrongWildcard"
                 maxBufferSize="65536"
                 maxBufferPoolSize="524288"
                 maxReceivedMessageSize="65536"
                 messageEncoding="Text"
                 textEncoding="utf-8"
                 transferMode="Buffered"
                 useDefaultWebProxy="true">
            <readerQuotas maxDepth="32"
                          maxStringContentLength="8192"
                          maxArrayLength="16384"
                          maxBytesPerRead="4096"
                          maxNameTableCharCount="16384" />
            <security mode="TransportWithMessageCredential">
                <transport clientCredentialType="None"
                           proxyCredentialType="None"
                           realm="" />
                <message clientCredentialType="UserName"
                         algorithmSuite="Default" />
            </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <client>
      <endpoint address="https://server.com/service/MyService.asmx"
      binding="basicHttpBinding" bindingConfiguration="MyService"
      contract="MyService.MyServiceInterface"
      name="MyService" />
    </client>
</system.serviceModel>

  改为

1
2
3
4
5
6
BasicHttpBinding binding = new BasicHttpBinding();
Uri endpointAddress = new Uri("https://server.com/service/MyService.asmx");
 
ChannelFactory<MyService.MyServiceInterface> factory = new ChannelFactory<MyService.MyServiceInterface>(binding, endpointAddress);
 
MyService.MyServiceInterface proxy = factory.CreateChannel();

 完善为

1
2
3
4
5
6
7
8
9
10
11
BasicHttpBinding binding = new BasicHttpBinding();
        binding.Security.Mode = BasicHttpSecurityMode.TransportWithMessageCredential;
        Uri endpointAddress = new Uri("https://server.com/Service.asmx");
 
        ChannelFactory<MyService.MyServiceInterface> factory = new ChannelFactory<MyService.MyServiceInterface>(binding, endpointAddress.ToString());
        factory.Credentials.UserName.UserName = "username";
        factory.Credentials.UserName.Password = "password";
 
        MyService.MyServiceInterface client = factory.CreateChannel();
 
        // make use of client to call web service here...

 示例2:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<bindings>
    <customBinding>
        <binding name="lbinding">
            <security  authenticationMode="UserNameOverTransport"
                messageSecurityVersion="WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11"
                securityHeaderLayout="Strict"
                includeTimestamp="false"
                requireDerivedKeys="true"
                keyEntropyMode="ServerEntropy">
            </security>
            <textMessageEncoding messageVersion="Soap11" />
            <httpsTransport authenticationScheme ="Negotiate" requireClientCertificate ="false" realm =""/>
        </binding>
    </customBinding>
</bindings>

 改为:

1
2
3
4
5
6
7
8
9
10
11
12
Uri epUri = new Uri(_serviceUri);
CustomBinding binding = new CustomBinding();
SecurityBindingElement sbe = SecurityBindingElement.CreateUserNameOverTransportBindingElement();
sbe.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11;       
sbe.SecurityHeaderLayout = SecurityHeaderLayout.Strict;
sbe.IncludeTimestamp = false;
sbe.SetKeyDerivation(true);
sbe.KeyEntropyMode = System.ServiceModel.Security.SecurityKeyEntropyMode.ServerEntropy;
binding.Elements.Add(sbe);
binding.Elements.Add(new TextMessageEncodingBindingElement(MessageVersion.Soap11, System.Text.Encoding.UTF8));
binding.Elements.Add(new HttpsTransportBindingElement());
EndpointAddress endPoint = new EndpointAddress(epUri);

 辅助函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public static TResult UseService<TChannel, TResult>(string url,
                                                    EndpointIdentity identity,
                                                    NetworkCredential credential,
                                                    Func<TChannel, TResult> acc)
{
    var binding = new BasicHttpBinding();
    binding.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
    binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
    var endPointAddress = new EndpointAddress(new Uri(url), identity,
                                              new AddressHeaderCollection());
    var factory = new ChannelFactory<T>(binding, address);
    var loginCredentials = new ClientCredentials();
    loginCredentials.Windows.ClientCredential = credentials;
 
    foreach (var cred in factory.Endpoint.EndpointBehaviors.Where(b => b is ClientCredentials).ToArray())
        factory.Endpoint.EndpointBehaviors.Remove(cred);
 
    factory.Endpoint.EndpointBehaviors.Add(loginCredentials);
    TChannel channel = factory.CreateChannel();
    bool error = true;
    try
    {
        TResult result = acc(channel);
        ((IClientChannel)channel).Close();
        error = false;
        factory.Close();
        return result;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
        return default(TResult);
    }
    finally
    {
        if (error)
            ((IClientChannel)channel).Abort();
    }
}

 调用方法:

usage

NameSpace.UseService("http://server/XRMDeployment/2011/Deployment.svc",
                     Identity,
                     Credentials,
(IOrganizationService context) =>
{ 
   ... your code here ...
   return true;
});
示例3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//end point setup
System.ServiceModel.EndpointAddress EndPoint = new System.ServiceModel.EndpointAddress("http://Domain:port/Class/Method");
System.ServiceModel.EndpointIdentity EndpointIdentity = default(System.ServiceModel.EndpointIdentity);
 
//binding setup
System.ServiceModel.BasicHttpBinding binding = default(System.ServiceModel.BasicHttpBinding);
 
binding.TransferMode = TransferMode.Streamed;
//add settings
binding.MaxReceivedMessageSize = int.MaxValue;
binding.ReaderQuotas.MaxArrayLength = int.MaxValue;
binding.ReaderQuotas.MaxBytesPerRead = int.MaxValue;
binding.ReaderQuotas.MaxDepth = int.MaxValue;
binding.ReaderQuotas.MaxNameTableCharCount = int.MaxValue;
binding.MaxReceivedMessageSize = int.MaxValue;
binding.ReaderQuotas.MaxStringContentLength = int.MaxValue;
 
binding.MessageEncoding = WSMessageEncoding.Text;
binding.TextEncoding = System.Text.Encoding.UTF8;
binding.MaxBufferSize = int.MaxValue;
binding.MaxBufferPoolSize = int.MaxValue;
binding.MaxReceivedMessageSize = int.MaxValue;
binding.SendTimeout = new TimeSpan(0, 10, 0);
binding.ReceiveTimeout = new TimeSpan(0, 10, 0);
 
//setup for custom binding
System.ServiceModel.Channels.CustomBinding CustomBinding = new System.ServiceModel.Channels.CustomBinding(binding);

 

What I do to configure my contract:

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0"), System.ServiceModel.ServiceContractAttribute(Namespace = "http://MyNameSpace", ConfigurationName = "IHostInterface")]
public interface IHostInterface
{
}


posted on   武胜-阿伟  阅读(275)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
历史上的今天:
2014-02-12 FileZilla 425 Can't open data connection
2013-02-12 交易系统 转
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示