当用户访问我的 webapi 应用程序时,我需要捕获用户的域\用户名。在我的开发机器上,我的 webapi 位于localhost:10570
和我的 angularjs 网站,它调用网络服务localhost:34575
.
如果我直接调用我的 webapi 应用程序,一切正常。我可以看到用户的域和用户名,并且服务以 JSON 形式返回请求的数据。但是,如果我访问我的 angularjs 站点并且 Angular 调用了 webapi,那么每次针对该服务的调用都会收到 401 未经授权的错误。
在我的 Web Api 应用程序 web.config 中,我有:
<system.web>
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
<authentication mode="Windows" />
</system.web>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="http://localhost:34575" />
<add name="Access-Control-Allow-Methods" value="POST, PUT, DELETE, GET, OPTIONS" />
<add name="Access-Control-Allow-Headers" value="content-Type, accept, origin, X-Requested-With, Authorization, name" />
<add name="Access-Control-Allow-Credentials" value="true" />
</customHeaders>
</system.webServer>
我在 IIS Express for Visual Studio 2015 的 applicationhost.config 文件中包含以下内容:
<location path="MyNamespace.WebAPI">
<system.webServer>
<security>
<authentication>
<windowsAuthentication enabled="true" />
<anonymousAuthentication enabled="false" />
</authentication>
</security>
</system.webServer>
</location>
我的 angularjs 网站是“MyNamespace.Client”中同一解决方案的一部分。
为什么直接访问Web服务可以正常工作,但通过Angular应用程序访问却失败?