Asp.net mvc authorize attribute integrated with a

2019-07-03 22:45发布

问题:

I want to use an [Authorize()] attribute in the following way on an action:

[Authorize(Roles = "Administrator" or UserId == id)]
public ActionResult Edit(int id){ }

Right now I'm using logics like this:

    public ActionResult Edit(int id)
    {
        if (User.IsInRole("Administrator") || User.Identity.Name.Equals(id))
        { }
    }

回答1:

No, but you an access everything piece of functionality the controller has inside the Attribute:

See:

How to pass parameters to a custom ActionFilter in ASP.NET MVC 2?



回答2:

You can't. In .NET attributes can use only constant values. On the other hand you could write a custom authorize attribute deriving from the standard one and in the AuthorizeCore method implement this logic.