如何在配置文件中不设置设置的情况下创建WCF客户端?

如何解决如何在配置文件中不设置设置的情况下创建WCF客户端?

| 我一个月前才开始从事WCF。如果我要求已经回答的问题,请原谅我。我尝试先搜索,但一无所获。 我读了这篇文章,“ WCF文件传输:IIS中托管的流和分块通道”。效果很好。现在,我想将客户端代码集成到应用程序中,该代码是在AutoCAD中运行的dll。如果要使用配置文件,则必须更改acad.exe.config,我认为这不是一个好主意。所以我认为如果可能的话,我想将配置文件中的所有代码都移到代码中。 这是配置文件:
<?xml version=\"1.0\" encoding=\"utf-8\" ?>
<configuration>
<system.serviceModel>
    <bindings>
        <basicHttpBinding>
            <binding name=\"BasicHttpBinding_IService\" 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=\"Mtom\" textEncoding=\"utf-8\" transferMode=\"Buffered\"
                useDefaultWebProxy=\"true\">
                <readerQuotas maxDepth=\"32\" maxStringContentLength=\"8192\" maxArrayLength=\"16384\"
                    maxBytesPerRead=\"4096\" maxNameTableCharCount=\"16384\" />
                <security mode=\"None\">
                    <transport clientCredentialType=\"None\" proxyCredentialType=\"None\"
                        realm=\"\" />
                    <message clientCredentialType=\"UserName\" algorithmSuite=\"Default\" />
                </security>
            </binding>
        </basicHttpBinding>
    </bindings>
    <client>
        <endpoint address=\"http://10.1.13.15:88/WCFStreamUpload/service.svc/ep1\"
            binding=\"basicHttpBinding\"
            bindingConfiguration=\"BasicHttpBinding_IService\"
            contract=\"MGFileServerClient.IService\"
            name=\"BasicHttpBinding_IService\" />
    </client>
</system.serviceModel>
你能帮我做这个改变吗?     

解决方法

        您可以在代码内进行所有设置,前提是您不需要将来更改此设置的灵活性。 您可以阅读有关在MSDN上设置端点的信息。虽然这适用于服务器,但端点和绑定的配置也适用于客户端,只是您使用不同的类。 基本上,您想做类似的事情:
// Specify a base address for the service
EndpointAddress endpointAdress = new EndpointAddress(\"http://10.1.13.15:88/WCFStreamUpload/service.svc/ep1\");
// Create the binding to be used by the service - you will probably want to configure this a bit more
BasicHttpBinding binding1 = new BasicHttpBinding();
///create the client proxy using the specific endpoint and binding you have created
YourServiceClient proxy = new YourServiceClient(binding1,endpointAddress);
显然,您可能希望使用与上面的配置相同的方式来配置具有安全性,超时等的绑定(您可以在MSDN上阅读有关BasicHttpBinding的内容),但这将使您朝着正确的方向前进。     ,        这完全是基于代码的配置和工作代码。您不需要客户端的任何配置文件。但是至少您在那里需要一个配置文件(可能会自动生成,您不必考虑这一点)。所有配置设置都在此处通过代码完成。
public class ValidatorClass
{
    WSHttpBinding BindingConfig;
    EndpointIdentity DNSIdentity;
    Uri URI;
    ContractDescription ConfDescription;

    public ValidatorClass()
    {  
        // In constructor initializing configuration elements by code
        BindingConfig = ValidatorClass.ConfigBinding();
        DNSIdentity = ValidatorClass.ConfigEndPoint();
        URI = ValidatorClass.ConfigURI();
        ConfDescription = ValidatorClass.ConfigContractDescription();
    }


    public void MainOperation()
    {
        var Address = new EndpointAddress(URI,DNSIdentity);
        var Client = new EvalServiceClient(BindingConfig,Address);
        Client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.PeerTrust;
        Client.Endpoint.Contract = ConfDescription;
        Client.ClientCredentials.UserName.UserName = \"companyUserName\";
        Client.ClientCredentials.UserName.Password = \"companyPassword\";
        Client.Open();

        string CatchData = Client.CallServiceMethod();

        Client.Close();
    }



    public static WSHttpBinding ConfigBinding()
    {
        // ----- Programmatic definition of the SomeService Binding -----
        var wsHttpBinding = new WSHttpBinding();

        wsHttpBinding.Name = \"BindingName\";
        wsHttpBinding.CloseTimeout = TimeSpan.FromMinutes(1);
        wsHttpBinding.OpenTimeout = TimeSpan.FromMinutes(1);
        wsHttpBinding.ReceiveTimeout = TimeSpan.FromMinutes(10);
        wsHttpBinding.SendTimeout = TimeSpan.FromMinutes(1);
        wsHttpBinding.BypassProxyOnLocal = false;
        wsHttpBinding.TransactionFlow = false;
        wsHttpBinding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
        wsHttpBinding.MaxBufferPoolSize = 524288;
        wsHttpBinding.MaxReceivedMessageSize = 65536;
        wsHttpBinding.MessageEncoding = WSMessageEncoding.Text;
        wsHttpBinding.TextEncoding = Encoding.UTF8;
        wsHttpBinding.UseDefaultWebProxy = true;
        wsHttpBinding.AllowCookies = false;

        wsHttpBinding.ReaderQuotas.MaxDepth = 32;
        wsHttpBinding.ReaderQuotas.MaxArrayLength = 16384;
        wsHttpBinding.ReaderQuotas.MaxStringContentLength = 8192;
        wsHttpBinding.ReaderQuotas.MaxBytesPerRead = 4096;
        wsHttpBinding.ReaderQuotas.MaxNameTableCharCount = 16384;

        wsHttpBinding.ReliableSession.Ordered = true;
        wsHttpBinding.ReliableSession.InactivityTimeout = TimeSpan.FromMinutes(10);
        wsHttpBinding.ReliableSession.Enabled = false;

        wsHttpBinding.Security.Mode = SecurityMode.Message;
        wsHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
        wsHttpBinding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
        wsHttpBinding.Security.Transport.Realm = \"\";

        wsHttpBinding.Security.Message.NegotiateServiceCredential = true;
        wsHttpBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
        wsHttpBinding.Security.Message.AlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Basic256;
       // ----------- End Programmatic definition of the SomeServiceServiceBinding --------------

       return wsHttpBinding;

   }

   public static Uri ConfigURI()
   {
       // ----- Programmatic definition of the Service URI configuration -----
       Uri URI = new Uri(\"http://localhost:8732/Design_Time_Addresses/TestWcfServiceLibrary/EvalService/\");

       return URI;
   }

   public static EndpointIdentity ConfigEndPoint()
   {
       // ----- Programmatic definition of the Service EndPointIdentitiy configuration -----
       EndpointIdentity DNSIdentity = EndpointIdentity.CreateDnsIdentity(\"tempCert\");

       return DNSIdentity;
   }


   public static ContractDescription ConfigContractDescription()
   {
        // ----- Programmatic definition of the Service ContractDescription Binding -----
        ContractDescription Contract = ContractDescription.GetContract(typeof(IEvalService),typeof(EvalServiceClient));

        return Contract;
   }
}
    ,        您是否要保留自定义配置并在您的应用程序中引用它?您可以尝试这篇文章:从自定义位置读取WCF配置(关于WCF) 否则,您可以使用ConfigurationManager.OpenExeConfiguration。     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-