WCF 错误 {"The username is not provided. Specify username in ClientCredentials."}

WCF Error {"The username is not provided. Specify username in ClientCredentials."}

我在 IIS 中托管了一个 WCF 网络服务。这是相同的配置:

当我尝试在我的 WinForms 客户端中使用此特定服务(添加为服务引用时)时,它抛出此异常:

The username is not provided. Specify username in ClientCredentials.

但是当我将服务添加为 "web reference" 时,我可以完美地执行所有方法。

<system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="BasicHttpEndpointBinding">
          <security mode="TransportCredentialOnly">
            <transport clientCredentialType="Basic" />
            <message clientCredentialType="UserName" algorithmSuite="Default" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>

      <services>
        <service behaviorConfiguration="EMSServiceBehavior"
                               name="EMSService.EMSCRUD">
          <endpoint address="" binding="basicHttpBinding"
          bindingConfiguration="BasicHttpEndpointBinding"
          name="BasicHttpEndpoint" contract="EMSService.IEMSCRUD">
          </endpoint>
        </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="EMSServiceBehavior">
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false" />
          <!--<serviceCredentials>
            <windowsAuthentication allowAnonymousLogons="False" includeWindowsGroups="True"/>
          </serviceCredentials>-->
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

添加为服务参考时的代码:

        EE.EMSCRUDClient obj = new EE.EMSCRUDClient();
        obj.ClientCredentials.Windows.ClientCredential.UserName = "demo";
        obj.ClientCredentials.Windows.ClientCredential.Password = "demo";
        obj.ClientCredentials.Windows.ClientCredential.Domain = "demo";
        obj.somemethod(); //Error here

添加为网络参考时的代码:

        testEMService.EMSCRUD ob = new testEMService.EMSCRUD();
        ICredentials credentials = new NetworkCredential("user", "pass");
        ob.Credentials = credentials;
        ob.somemethod();//No error

首先,您可以在配置中将安全模式更改为 Transport 而不是 TransportCredentialOnly(如果没有特殊原因)。 其次,我确信它会导致错误,因为您在代码中的 Windows 级别设置了凭据。应该是:

obj.ClientCredentials.UserName.UserName = "user";
obj.ClientCredentials.UserName.Password = "pass";