2016-09-07 34 views
0

我正在使用ChannelFactory調用WCF服務(因爲目標服務位置將根據環境而改變,我需要可配置的URL)。但是我得到的錯誤:通過channelfactory調用WCF webservice時出錯 - 未經許可

The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Negotiate,NTLM'.

我的調用代碼

var myBinding = new BasicHttpBinding(); 
var myEndpoint = new EndpointAddress(webserviceAddress); 
var myChannelFactory = new ChannelFactory<IObjectService>(myBinding, myEndpoint); 
var serviceClient = myChannelFactory.CreateChannel(); 

我的WCF服務的web.config system.servicemodel部分

<system.serviceModel> 
    <behaviors> 
     <serviceBehaviors> 
     <behavior> 
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/> 
      <serviceDebug includeExceptionDetailInFaults="true"/> 
     </behavior> 
     </serviceBehaviors> 
    </behaviors> 
    <bindings> 
     <basicHttpBinding> 
     <binding> 
      <security mode="TransportCredentialOnly"> 
      <transport clientCredentialType="Windows"/> 
      </security> 
     </binding> 
     </basicHttpBinding> 
    </bindings> 
    <protocolMapping> 
     <add binding="basicHttpsBinding" scheme="https" /> 
    </protocolMapping> 
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" minFreeMemoryPercentageToActivateService="0" /> 
    </system.serviceModel> 

服務應基於Windows身份驗證進行身份驗證。默認情況下,上面的調用代碼會使用Windows身份驗證來傳遞代碼以(服務帳戶)身份運行的帳戶,但它似乎在發送匿名消息

+0

您的服務是否託管在IIS中?是否禁用匿名身份驗證? – Tim

回答

0

您必須設置使用消息憑據傳輸的模式,如在下面的代碼所示:

var myBinding = new BasicHttpBinding(); 
myBinding.Security.Mode = SecurityMode.TransportCredentialOnly; 

作爲替代方案,可以在結合的構造設置的模式:

var myBinding = new BasicHttpBinding(SecurityMode.TransportCredentialOnly); 

另外設置ClientCredential:

myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows; 
+0

謝謝,這有幫助。雖然該消息憑證選項僅適用於我沒有的HTTPS,但只有HTTP。我嘗試過TransportCredentialOnly,但它說綁定之間不匹配,即使TransportCredentialOnly是我在我的web.config? – NZJames

+0

你說得對,我在Security.Mode上犯了一個錯誤。我已經更新了我的答案。你能否發佈整個錯誤信息? –