MVC: creating a custom [AuthorizeAttribute] which takes parameters?

瘦欲@ 提交于 2019-12-02 20:55:16

问题


Here is my problem:

I'm authorizing users on their roles, for 1 part.

 [Authorize(Roles = "Admin,...")]
 public class ModulesController : Controller {
    .....
 }

the Modules controller shows a list of modules which the user has right to. (there are a LOT of modules, but the user is only connected to a part of them). there are a load of things coupled to the modules, like questions, ...

for example: the details view of the Modules controller.

    public ActionResult Details(int id) {
        var mod = (from p in _db.Modules
                   where p.Mod_ID == id
                   select p).First();

        return accessible(mod);
    }

    [NonAction]
    public ActionResult accessible(Module p) {
        if (MvcApplication.accessible(HttpContext.User, p.Mod_ID)) {
            return View(p);
        }
        ViewData["delError"] = "Not Accessible";
        return View("Error");
    }

with this code I check whether this user is coupled to the specified module which he requested to see its details.

I do not like this method, as I don't always return a Module in my view so this has a lot of overload methods, and for the sub pages of the modules, like the Questions, i also need to check that the person is looking at the questions of a module he has access to.

I'd like to do this with an authorize attribute, which would take the ID from the Module, and with that would grant or deny access to that certain module. My problem is, when a user requests to see a question, i need to figure out the module ID with some code. Sometimes the moduleID is in the url, but this is not always the case.

how would i do this ? would it be good to try and use the attribute? or do I need to do this differently?

Edit:

i'm trying what is being suggested in the answers, but how do i get routedata (like ID) in the controllers constructor?


回答1:


See: Asp.net mvc authorize attribute integrated with a parameter

Really bummed the related search doesn't pick up on these things...



来源:https://stackoverflow.com/questions/4681486/mvc-creating-a-custom-authorizeattribute-which-takes-parameters

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