asp.net-mvc - 以编程方式在 IIS 中启用或禁用匿名身份验证

标签 asp.net-mvc authentication iis forms-authentication windows-authentication

我有一个 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/

相关文章:

c# - 带字符串数组的串联 Where 子句

c# - Razor:使用其他应用程序的布局文件

asp.net-mvc - 使用存储库模式时的多个数据库上下文

C# Linq 将对象属性转换为数组

jquery - 自定义摘要身份验证

azure - 在 Xamarin 和 Microsoft Authenticator 中使用 ADAL for .NET 进行身份验证在 iOS 上失败

IIS 7.5 将请求指向错误的物理路径

iis - 如何使用 IIS7 服务器在亚马逊 EC2 Windows 实例上托管域名

c# - 无法使用 Automapper 将第二个实体添加到 ViewModel 中?

authentication - 如何在配置为使用 LDAP 作为用户数据库的 Jenkins 上添加外部用户?