如何使用WCF服务的代理实现读取类库中的System.serviceModel

问题描述 投票:0回答:1

我试图从库的app.config文件中读取类库中的服务配置。但要低于例外

找不到名为“WSHttpBinding_IUsers”的端点元素,并在ServiceModel客户端配置部分中收缩“ISGP.Plugins.SolveService.IUsers”。这可能是因为没有为您的应用程序找到配置文件,或者因为在客户端元素中找不到与此名称匹配的端点元素。

我尝试实现以下代码来读取配置并创建客户端

 public class ServiceManager
{
    public static T CreateServiceClient<T>(string configName)
    {
       // string _assemblyLocation = Assembly.GetExecutingAssembly().Location;

        var configuration = ConfigurationManager.OpenMappedExeConfiguration(
                         new ExeConfigurationFileMap
                         {
                             ExeConfigFilename = "app.config"
                         }, ConfigurationUserLevel.None);

        ConfigurationChannelFactory<T> channelFactory = new ConfigurationChannelFactory<T>(configName, configuration, null);
        var client = channelFactory.CreateChannel();
        return client;
    }


}

调用此方法如下

    usersClient= (UsersClient)ServiceManager.CreateServiceClient<IUsersChannel>("WSHttpBinding_IUsers");
  usersClient.ClientCredentials.UserName.UserName = userName;
  usersClient.ClientCredentials.UserName.Password = password;

但它抛出了上面的异常app.config文件如下所示

 <system.serviceModel>
  <bindings>
    <wsHttpBinding>
      <binding name="WSHttpBinding_IUsers">
        <security mode="TransportWithMessageCredential">
          <transport clientCredentialType="None" />
          <message clientCredentialType="UserName" establishSecurityContext="false" />
        </security>
      </binding>
    </wsHttpBinding>
  </bindings>
  <client>
    <endpoint address="https://xxxxxx16.prod.xxxxx.local/WebServices/v3/Users.svc"
        binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IUsers"
        contract="ISGP.Plugins.SolveService.IUsers" name="WSHttpBinding_IUsers" />
  </client>
</system.serviceModel>
c# wcf windows-services wcf-binding
1个回答
0
投票

请在通道工厂构造函数中传递endpoint参数。

ConfigurationChannelFactory channelFactory = new ConfigurationChannelFactory(configName,configuration,null);

您可以参考以下代码。

ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = "app.config";
            Configuration newConfiguration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            ConfigurationChannelFactory<IService> factory = new ConfigurationChannelFactory<IService>("endpoint1", newConfiguration, new EndpointAddress("http://localhost:8000/servicemodelsamples/service"));
            factory.Credentials.UserName.UserName = "jack";
            factory.Credentials.UserName.Password = "123456";
            IService client1 = factory.CreateChannel();

https://docs.microsoft.com/en-us/dotnet/framework/wcf/samples/configuration-channel-factory 如果有什么我可以帮忙,请随时告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.