Specifying Roles in web.config of an asp.net MVC application

三世轮回 提交于 2019-11-28 06:53:37

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")]

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>

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

Please have a look at this excellent example, in which author talks about the problem you are facing.

http://www.ryanmwright.com/2010/04/25/dynamic-controlleraction-authorization-in-asp-net-mvc/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!