2008-09-18 118 views
12

说我有以下的web.config:检测Web.Config中身份验证模式

<?xml version="1.0" encoding="utf-8"?> 
<configuration> 
    <system.web> 
     <authentication mode="Windows"></authentication> 
    </system.web> 
</configuration> 

使用ASP.NET C#,如何检测认证标签的模式价值?

回答

4

尝试Context.User.Identity.AuthenticationType

转到了PB的回答乡亲

+0

我必须这样做接受你的回答,因为你的回答是最快的,并且有效:) – GateKiller 2008-09-18 12:17:44

+1

Thi s是错误的。在一般情况下,IIdentity.AuthenticationType可以包含任何字符串,它可能不一定与web.config中设置的身份验证模式相匹配。 我会使用@pb的解决方案。 – Joe 2008-09-18 13:48:13

-2

使用xpath查询//configuration/system.web/authentication[mode]?

protected void Page_Load(object sender, EventArgs e) 
{ 
XmlDocument config = new XmlDocument(); 
config.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); 
XmlNode node = config.SelectSingleNode("//configuration/system.web/authentication"); 
this.Label1.Text = node.Attributes["mode"].Value; 
} 
+1

不,这在一般情况下不起作用。 ASP.NET应用程序从machine.Config和虚拟目录树中更高级别的所有其他web.config文件继承设置:请参阅http://msdn.microsoft.com/en-us/library/ms178685.aspx 您的技术只看最低的web.config文件。 – Joe 2008-09-18 13:38:41

+1

XPath不是用来以任何方式解析配置的东西。利用MS提供的库是一种更加高效和可维护的方法。以上评论是一个完美的例子,为什么不使用它以及事实并非所有平台都必须使用配置文件进行身份验证或其他设置;另一个有效的情况是,如果身份验证类型的位置发生更改,则必须替换硬编码的字符串,重新编译并重新分发。 – 2016-03-28 21:18:11

11

导入System.Web.Configuration命名空间,这样做:

var configuration = WebConfigurationManager.OpenWebConfiguration("/"); 
var authenticationSection = (AuthenticationSection)configuration.GetSection("system.web/authentication"); 
if (authenticationSection.Mode == AuthenticationMode.Forms) 
{ 
    //do something 
} 
2

您还可以通过使用静态ConfigurationManager类来获取部分获得认证模式,然后枚举AuthenticationMode

AuthenticationMode authMode = ((AuthenticationSection) ConfigurationManager.GetSection("system.web/authentication")).Mode;

The difference between WebConfigurationManager and ConfigurationManager


如果你想在指定的枚举检索常量的名称,你可以通过使用Enum.GetName(Type, Object)方法

Enum.GetName(typeof(AuthenticationMode), authMode); // e.g. "Windows"