MVC:创建一个带有参数的自定义 [AuthorizeAttribute]?
这是我的问题:
我正在授权用户的角色,一部分。
[Authorize(Roles = "Admin,...")]
public class ModulesController : 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");
}
使用此代码,我检查该用户是否耦合到他请求查看其详细信息的指定模块。
我不喜欢这种方法,因为我并不总是返回 Module
在我看来,所以这有很多重载方法,并且对于模块的子页面,例如问题,我也需要检查该人是否正在查看他有权访问的模块的问题。
我想使用授权属性来执行此操作,该属性将从模块获取 ID,并通过该属性授予或拒绝对该特定模块的访问。我的问题是,当用户请求查看问题时,我需要使用一些代码找出模块 ID。有时 moduleID 位于 url 中,但情况并非总是如此。
我该怎么做?尝试使用该属性会好吗?或者我需要采取不同的做法吗?
编辑:
我正在尝试答案中建议的内容,但是如何在控制器构造函数中获取路由数据(如ID)?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请参阅: Asp.net mvc 授权属性集成参数
真的很遗憾相关搜索没有找到这些东西......
See: Asp.net mvc authorize attribute integrated with a parameter
Really bummed the related search doesn't pick up on these things...