如何在登录页面上获取安全页面的访问角色列表?
答案 0 :(得分:1)
// Parse original url
var originalUrl = FormsAuthentication.GetRedirectUrl(User.Identity.Name, false);
var originalUrlArray = originalUrl.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
var pathToWebConfig = "~";
for (int i = 0; i < originalUrlArray.Length - 1; i++) {
pathToWebConfig += "/" + originalUrlArray[i];
}
var locationName = originalUrlArray[originalUrlArray.Length - 1];
// Get web config
var remoteWebConfig = (System.Configuration.Configuration)WebConfigurationManager.OpenWebConfiguration(pathToWebConfig);
// Find authorization section
AuthorizationSection authorizationSection = new AuthorizationSection();
foreach (ConfigurationLocation location in remoteWebConfig.Locations) {
if (location.Path.Equals(locationName)) {
authorizationSection = (AuthorizationSection)location.OpenConfiguration().GetSection("system.web/authorization");
break;
}
}
// Get roles
var listOfRoles = new List<string>();
foreach (AuthorizationRule rule in authorizationSection.Rules) {
if (rule.Action != AuthorizationRuleAction.Allow) {
continue;
}
foreach (var role in rule.Roles) {
listOfRoles.Add(role);
}
}