ASP.NET MVC:问题设置授权属性角色从一个变量,常量需要 [英] ASP.NET MVC: Problem setting the Authorize attribute Role from a variable, requires const

查看:142
本文介绍了ASP.NET MVC:问题设置授权属性角色从一个变量,常量需要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题,设置授权从变量属性的角色值。该错误消息说,它需要一个const变量。当我创建一个const类型的变量,它工作正常,但我试图加载从Web.config文件或其他任何将允许最终用户设置此值。我使用的是集成的Windows身份验证,因为这是一个Intranet唯一的应用程序。

有没有办法来检查从控制器用户的角色?我会用这一个if语句来验证,而不是一个属性。

  [授权(角色= Config.GMPUser)
公众的ActionResult指数()
   {
      返回查看();
   }


解决方案

您可以在控制器中使用 User.InRole(角色名)

编辑:下面的code不会因为GetCustomAttributes工作()显然返回每个属性,而不是实际属性的引用的副本。留给答案为其他答案提供上下文。

至于在授权属性设置它,我唯一的想法是将其设置为在属性定义为空字符串,然后对控制器的类型反射来获取并修改相应的AuthorizeAttribute的CustomAttribute财产(也就是说,其类型为AuthorizeAttribute的)每个你关心的方法。你应该能够在角色属性设置为配置项的方式。

  VAR属性= typeof运算(myController的).GetMethod(「指数」)
                                     .GetCustomAttributes(typeof运算(AuthorizeAttribute)
                                                          假)
                 作为AuthorizeAttribute;属性[0] = .Roles Config.GMPUser;

我想,你这样做,尤其在应用程序启动您的Global.asax文件,这样只需要进行一次。

I am having a problem setting the Authorize attribute Role value from a variable. The error message says it requires a const variable. When I create a const type variable it works fine but I am trying to load the value from the Web.Config file or anything else that will allow the end user to set this. I'm using integrated Windows authentication since this is an intranet only application.

Is there a way to check the users role from a controller? I will use this in an if statement to authenticate instead of an attribute.

[Authorize(Roles = Config.GMPUser)]
public ActionResult Index()
   {
      return View();
   }

解决方案

You can use User.InRole( "RoleName" ) within a controller.

EDIT: The code below will not work since GetCustomAttributes() apparently returns a copy of each attribute instead of a reference to the actual attribute. Left as answer to provide context for other answers.

As far as setting it in the authorize attribute, the only idea that I have is to set it to the empty string in the attribute definition, then use reflection on the controller's type to get and modify the CustomAttribute property corresponding to the AuthorizeAttribute (i.e., the one whose type is AuthorizeAttribute) for each method you care about. You should be able to set the Roles property to your configuration item that way.

var attributes = typeof(MyController).GetMethod("Index")
                                     .GetCustomAttributes(typeof(AuthorizeAttribute),
                                                          false)
                 as AuthorizeAttribute;

attributes[0].Roles = Config.GMPUser;

I suppose that you would do this in your Global.asax file on application start so that it only needs to be done once.

这篇关于ASP.NET MVC:问题设置授权属性角色从一个变量,常量需要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆