本文介绍了在一个asp.net MVC应用程序的web.config文件中指定角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建与窗体身份验证MVC应用程序。我对认证活动目录等方面都创造了一个自定义的RoleProvider。我的应用程序只涉及一小部分而到现在为止,我一直在我的web.config的appSettings部分定义角色的:

I am creating an MVC application with forms auth. I am authenticating against active directory and so have created a custom RoleProvider. My application is only concerned with a small set of roles which up until now I have been defining in the appSettings section of my web.config:

<appSettings>
  <add key="DirectorRole" value="Domain\Directors" />
  <add key="ManagementRole" value="Domain\Managers" />
  ...
</appSettings>

不过,我遇到了一对夫妇使用这种方法的问题:

However I have run into a couple of problems with this approach:


  1. 我无法引用这些在我的位指示数据注解设置: [授权(角色= ConfigurationManager.AppSettings [DirectorRole])] ,因为它不会编译,所以我要再次指定组的名称: [授权(角色=域名\\\\董事」)]

  2. 在我的web.config,我想指定groupsToUse为我的角色提供程序,只是引用pre-现有列表,而不是维持两个单独列出了同一组的角色的。

  1. I cannot reference these setting in my contoller data annotations: [Authorize(Roles = ConfigurationManager.AppSettings["DirectorRole"])] as it wont compile so I have to specify the name of the group again: [Authorize(Roles = "Domain\\Directors")].
  2. In my web.config, I would like to specify the groupsToUse for my role provider and just reference a pre-existing list, rather than maintain two seperate lists of the same set of roles.

似乎有必须定义在web.config中的角色,更好的/可重复使用的办法,有人可以点我在正确的方向吗?

It seems that there must be a better/reusable way to define the roles in the web.config, can someone point me in the right direction please?

推荐答案

我会使用自定义属性授权preFER。像这样的。

I would prefer using a custom authorize attribute. Like this one.

public class MyAuthorizeAttribute : AuthorizeAttribute {

    public MyAuthorizeAttribute(params string[] roleKeys) {
        List<string> roles = new List<string>(roleKeys.Length);

        //foreach(var roleKey in roleKeys) {
            //roles.Add(ConfigurationManager.AppSettings["DirectorRole"]);
        //}
        var allRoles = (NameValueCollection)ConfigurationManager.GetSection("roles");
        foreach(var roleKey in roleKeys) {
            roles.Add(allRoles[roleKey]);
        }

        this.Roles = string.Join(",", roles);
    }
}

在你的控制器,使用方法:

In your controller, use:

[MyAuthorize("DirectorRole")]

在你的web.config

In your web.config

  <configSections>
    <section
      name="roles"
      type="System.Configuration.NameValueFileSectionHandler,System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
  </configSections>

  <roles>
    <add key="DirectorRole" value="Domain\Directors" />
    <add key="ManagementRole" value="Domain\Managers" />
  </roles>

我希望这将解决您的第一个问题就好了。和twiking一点就能解决第二个了。

I hope this will solve your first problem just fine. And twiking a little will solve the second one too.

这篇关于在一个asp.net MVC应用程序的web.config文件中指定角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 09:19