属性参数必须是属性参数类型的常量表达式,typeof表达式或数组创建表达式

时间:2016-12-07 04:00:58

标签: c# asp.net-mvc authentication controller

我正在研究C#MVC项目,我对控制器上的操作使用了自定义授权方法,但是我需要传递控制器名称和Action,这是我到目前为止所做的,但是给了我标题上的错误,我该如何解决这个问题?

public class ServiceUpdateController : Controller
    {
        [AuthorizeRoles(Accion = "Index", ControllerProgram = System.Web.HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString() )]
        // GET: ServiceUpdate
        public ActionResult Index()
        {
            return View();
        }
    }

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

属性是元数据,必须在编译时知道,因此您只能使用常量(直到运行时才知道当前控制器)。

httpContext方法的protected override bool AuthorizeCore(HttpContextBase httpContext)参数包含有关当前请求的信息,因此您可以使用

protected override bool AuthorizeCore(HttpContextBase httpContext)
{
    string controller = httpContext.Request.RequestContext
        .RouteData.Values["controller"].ToString();
    ....
}
相关问题