Mitchell

update location element in web.config

<%@ Page Language="C#" %>

<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Web.Configuration" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            TestMethod();
        }       
    }

    /// <summary>
    /// TrackBack:http://forums.asp.net/t/1212943.aspx
    /// </summary>
    protected void TestMethod()
    {
        Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");
        String path = "Default.aspx";

        SetLocationAuthorization(config, path, AuthorizationRuleAction.Allow, "A Wen");
    }

    public static void SetLocationAuthorization(Configuration config, string path, AuthorizationRuleAction ara, String user)
    {
        foreach (ConfigurationLocation cl in config.Locations)
        {
            if (cl.Path.ToLower() == path.ToLower())
            {
                Configuration locConfig = cl.OpenConfiguration();

                SystemWebSectionGroup systemWeb = (SystemWebSectionGroup)locConfig.GetSectionGroup("system.web");
                AuthorizationSection section = (AuthorizationSection)systemWeb.Sections["authorization"];
                section.Rules.Clear();
                AuthorizationRule newRule = new AuthorizationRule(AuthorizationRuleAction.Allow);
                AuthorizationRule aRule = new AuthorizationRule(AuthorizationRuleAction.Deny);
                aRule.Roles.Add("administrator");
                newRule.Users.Add(user);
                newRule.Users.Add("wilpho");
                section.Rules.Add(newRule);
                section.Rules.Add(aRule);
                locConfig.Save();
            }
        }
        throw new Exception("Path not found : " + path);
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
        </div>
    </form>
</body>
</html>

posted on 2008-03-18 19:10  MitChell  阅读(333)  评论(0编辑  收藏  举报

导航