我有一个 Web 应用程序,我需要为其用户提供将登录方法从 FormsAuth 切换到 WindowsAuth 的选项。我设法通过代码更改了 web.config 文件:
Configuration config = WebConfigurationManager.OpenWebConfiguration(Url.Content("~"));
AuthenticationSection auth = ((AuthenticationSection)(config.SectionGroups["system.web"].Sections["authentication"]));
auth.Mode = AuthenticationMode.Windows; // Or Forms if I want to.
config.Save();
但问题是,当我使用 FormsAuth 时,我需要打开 Anonymouse Authentication 选项,而当我使用 WinAuth 时,我需要关闭它。我只是找不到通过代码更改该选项的方法。
互联网上的所有内容都说要这样做:
<security>
<authentication>
<anonymousAuthentication enabled="false/true" />
</authentication>
</security>
但是当我将其插入到我的 web 应用程序的 web.config 中时,它说配置错误。我读到这可能适用于另一个配置文件,例如 appHost.config 或类似的文件,但我更喜欢仅对我自己的应用程序进行更改,而不是对 IIS 进行更改,我希望您明白原因。
那么,我该怎么做呢?
最佳答案
您正在尝试更新错误的部分。 onymousAuthentication 是 system.webServer 的一部分,而不是 system.web。正确的配置是
<system.webServer>
<security>
<authentication>
<anonymousAuthentication enabled="true" />
</authentication>
</security>
</system.webServer>
您可以使用 Microsoft.Web.Administration 中的 ServerManager 类对其进行修改。搜索 block 包“Microsoft.Web.Administration”。使用 nugget 添加对 Microsoft.Web.Administration.dll 的引用后,您可以使用代码对其进行修改,如下所示:
using (ServerManager serverManager = new ServerManager())
{
Microsoft.Web.Administration.Configuration config = serverManager.GetApplicationHostConfiguration();
Microsoft.Web.Administration.ConfigurationSection anonymousAuthenticationSection = config.GetSection("system.webServer/security/authentication/anonymousAuthentication");
anonymousAuthenticationSection["enabled"] = true;
serverManager.CommitChanges();
}
关于asp.net-mvc - 以编程方式在 IIS 中启用或禁用匿名身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28419304/