我正在使用 C# 和 .NET Framework 4.5.1 开发一个带有 Web Api 服务的 ASP.NET MVC 5 应用。
我已启用<authentication mode="Windows" />
上Web.config
并在 ASP.NET MVC Controller 上添加了以下内容:
[Authorize(Roles = @"MyDomain\MyRole")]
public class ReportController : Controller
但我不需要 ApiController
上的 Windows 身份验证。如何启用对 ApiController
的匿名访问是吗?
最佳答案
要为 webapi 执行此操作,您可以在 Web.Config 中使用以下内容
<location path="api">
<system.web>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
</location>
这意味着对于 api Controller ,允许任何用户(用 ? 表示)。如果您想做特定的 Controller ,可能值得将其更改为更具体。
它还假设您拒绝所有匿名用户的访问,并且您的 web.config 身份验证如下
<system.web> <authentication mode="Windows" />
<authorization>
<deny users="?" />
</authorization> </system.web>
但是,如果您想在 MVC Controller 上允许它,您可以使用 [AllowAnonymous] 属性。
Disable Windows Authentication for WebAPI
Windows Authentication for ASP.NET MVC 4 - how it works, how to test it
补充阅读:
关于asp.net - 允许 ApiController 上的匿名应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30589585/