我在这个上扯了我的头发,我有一个 WCF 服务,我可以通过浏览器调用它并且它工作正常,当我使用以下方法从 Web 应用程序调用它时,我得到一个(401) 未经授权的错误。并且该服务不会被调用。更重要的是,当我从本地机器(使用 IIS Express 的调试模式)指向我的开发服务器(IIS7)运行我的 Web 应用程序时,它可以工作,但是当我将我的 Web 应用程序部署到开发服务器并将其指向开发服务器服务时因 401 错误而失败。我认为这与 IIS7 有关,但我不能 100% 确定,帮助会非常有用。
我已经在网上寻找答案,但到目前为止我发现的最好的是这个。
我的服务电话如下:
var request = (HttpWebRequest) WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "application/json; charset=utf-8";
request.AuthenticationLevel = AuthenticationLevel.MutualAuthRequested;
request.Credentials = CredentialCache.DefaultCredentials;
WebResponse responce = request.GetResponse();
Stream reader = responce.GetResponseStream();
var sReader = new StreamReader(reader);
string outResult = sReader.ReadToEnd();
sReader.Close();
var result = (T) JsonConvert.DeserializeObject(outResult, typeof (T));
return result;
我的服务配置如下所示:
<service name="RGMPServices.Householding.Services.AccountService" behaviorConfiguration="Default">
<endpoint address="" kind="webHttpEndpoint" endpointConfiguration="SecuredHttpEndpointBinding" contract="RGMPServices.Householding.Contracts.IAccountService" />
</service>
<service name="RGMPServices.Householding.Services.HouseholdService" behaviorConfiguration="Default">
<endpoint address="" kind="webHttpEndpoint" endpointConfiguration="SecuredHttpEndpointBinding" contract="RGMPServices.Householding.Contracts.IHouseholdService" />
</service>
<service name="RGMPServices.Householding.Services.UserService" behaviorConfiguration="Default">
<endpoint address="" kind="webHttpEndpoint" endpointConfiguration="SecuredHttpEndpointBinding" contract="RGMPServices.Householding.Contracts.IUserService" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="webBehaviour">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="Default">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="SecuredHttpEndpointBinding" helpEnabled="true" automaticFormatSelectionEnabled="true">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" />
</security>
</standardEndpoint>
</webHttpEndpoint>
</standardEndpoints>
我已经在客户端服务调用上记录了一些日志,就在我调用服务之前,响应是:
调试 2013-10-01 13:15:13,569 452ms ServiceGetSingle - 通过登录:MYLANDOMAIN\MYLANUSERNAME
错误 2013-10-01 13:15:13,631 514ms ServiceGetSingle - 使用用户凭据登录调用 ServiceGetSingle 时出错:MYLANDOMAIN\MYLANUSERNAME System.Net.WebException:远程服务器返回错误:(401)未经授权。在 System.Net.HttpWebRequest.GetResponse() 在 Householding.Common.ServiceHelper.ServiceGetSingle[T](字符串 url)
代码如下所示:
logger.Debug("Passing Login: "
+ System.Security.Principal.WindowsIdentity.GetCurrent().Name)
即使我将网站的 AppPool 设置为我的域帐户,它仍然没有授权我访问 WCF 服务,但同样:它适用于浏览器。太奇怪了!