【问题标题】:AllowAnonymous Attribute not working on Web API controllerAllowAnonymous 属性在 Web API 控制器上不起作用
【发布时间】:2015-08-10 22:34:59
【问题描述】:

我有一个用 ASP.NET MVC 4 编写的 Web 应用程序。它是一个 Intranet 应用程序,因此我使用的是 Windows 身份验证(匿名身份验证已关闭)。它将一些 Web API 服务暴露给其他 Web 应用程序。

问题是这些服务应该由来自其他应用程序的匿名用户访问。当我从浏览器调用服务时,一切正常(这很明显)。但是当我尝试通过另一个应用程序与服务通信时,它会返回 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>

但这也无济于事。在 web.config 我没有设置任何其他部分(我的意思是我没有任何授权块)。

有人知道发生了什么吗?为什么它不起作用?我将不胜感激有关如何解决此问题的任何信息。

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

[AllowAnonymous]
public class TestController : ApiController
{
    public string GetSayHello()
    {
        return "Hello world";
    }
}


问候。

【问题讨论】:

    标签: asp.net asp.net-web-api


    【解决方案1】:

    我的一位同事发现您必须使用实际 url 设置位置路径。
    例如,我有一个名为 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>
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 通过谷歌登陆这里。在 .Net Core 2.1 中遇到问题,我的 API 在未经授权的情况下返回,即使我在控制器上有 AllowAnonymous 属性。您的回答让我检查了 Visual Studio 中的设置。未选中启用匿名身份验证。检查一下就可以了。
      猜你喜欢
      • 1970-01-01
      • 2011-03-24
      • 2013-11-23
      • 2012-09-15
      • 1970-01-01
      • 2014-04-23
      • 2019-03-26
      • 2016-11-13
      • 2013-11-11
      相关资源
      最近更新 更多