AllowAnonymous属性不适用于Web API控制器

Rom*_*ska 10 asp.net asp.net-web-api

我有一个用ASP.NET MVC 4编写的Web应用程序.它是一个Intranet应用程序,因此我正在使用Windows身份验证(匿名身份验证已关闭).它向一些Web API应用程序公开了一些Web API服务.

问题是匿名用户应该从其他应用程序访问这些服务.当我从浏览器调用服务时,一切正常(很明显).但是当我尝试通过另一个应用程序与服务进行通信时,它会返回401.2错误.使用匿名属性装饰API控制器没有帮助.我也尝试在web.config中设置location元素,如下面的代码所示:

<location path="Controllers/Api">
<system.web>
  <authorization>
    <!-- All anonymous users access to the virtual path api -->
    <allow users="?" />
  </authorization>
</system.web>
<!-- Need to include the security overrides else it will inherit from the root of the application -->
<system.webServer>
  <security>
    <authentication>
      <!-- Need to enable anonymous access and turn off Windows authentication for the virtual path -->
      <anonymousAuthentication enabled="true"/>
      <windowsAuthentication enabled="false"/>
    </authentication>
  </security>
</system.webServer>
Run Code Online (Sandbox Code Playgroud)

但它也没有帮助.在web.config中我没有设置任何其他部分(我的意思是我没有任何授权块).

有谁知道发生了什么事?为什么不起作用?我将非常感谢有关如何解决此问题的任何信息.

这是我为测试目的而创建的Web API操作:

[AllowAnonymous]
public class TestController : ApiController
{
    public string GetSayHello()
    {
        return "Hello world";
    }
}
Run Code Online (Sandbox Code Playgroud)


问候.

Ari*_*rin 5

我的一位同事发现你必须用实际网址设置位置路径.
例如,我有一个名为exampleController的控制器,您可以像访问http://domain.com/api/example/method一样访问它.然后,将以下示例添加到web.config中.Visual Studio会抱怨,但它有效.

<location path="api/example/method">
  <system.web>
    <authorization>
      <allow users="?" />
    </authorization>
  </system.web>
</location>
Run Code Online (Sandbox Code Playgroud)


bea*_*der 2

检查 IIS 设置是否确实允许匿名访问。一定是服务器配置错误。一种替代方法是使用Fiddler进行调试。从应用程序的角度来看,您所做的一切都是正确的。