get parameters from URL in controller constructor
I need to write some code to find an ID in my database of a Project. Users are coupled to a project and all the projects have a lot of connections to other objects, such as Sessions.
Now I need to check before running any Actions, if the user trying to access the Session, is connected to the same project as the session is connected to.
For this i want to use an [Attribute] on the Actions. MVC: creating a custom [AuthorizeAttribute] which takes parameters?
This question and answer 开发者_高级运维got me started, but i'm having trouble using the constructor of the controller to get my Project ID
the goal is that i can write some code in each constructor, of all my controllers of objects depending on the Projects, find the project ID, and make it accessible (public), so my [customauthorize]
will have access to this project ID to check whether the user has access or not.
My problem:
public class SessionController : Controller {
NASDataContext _db = new NASDataContext();
public SessionController() {
var test = RouteData;
var ses = _db.Sessies.First(q=>q.Ses_ID==1);
}
How do I access my routedata? RouteData
is null, HttpContext
is null and Request
is null.
I need the ID in the url, which is in the routedata...
I would suggest placing this check in the Model rather than the Controller. In the Controller you'll need to decorate each action that requires this check, remember this is going execute code on every action you apply it to so you probably don't want to apply it at Controller level to start with. The simpler approach is to implement the check once in the Model then you have no 'concern' in your Controller for access rights. This will make the testing of this access right check possible as you'll only have the test in one place.
This is what i did now to fix it and i'm quite happy about it.
Module Partial:
public partial class Module {
public string FullName {
get {
return Mod_Code + " " + Mod_Titel;
}
}
public string ShortName {
get {
return Mod_Code;
}
}
public bool IsAccessible() {
return this.Projecten.IsAccessible();
}
}
Projects Partial:
public partial class Projecten {
public string FullName {
get {
if (Proj_Kortenaam == Proj_Naam)
return Proj_Kortenaam;
return Proj_Kortenaam + " " + Proj_Naam;
}
}
public string ShortName {
get {
return Proj_Kortenaam;
}
}
public bool IsAccessible() {
return IsAccessible(HttpContext.Current.User);
}
public bool IsAccessible(IPrincipal user) {
//this code checks if the user can access or not
return MvcApplication.projectToegankelijk(user, this._Proj_ID);
}
}
then in the Modules controller
[NonAction]
public ActionResult noRights() {
ViewData["delError"] = "You have no rights.";
return View("Error");
}
//
// GET: /Modules/Details/5
public ActionResult Details(int id) {
var mod = _db.Modules.First(q => q.Mod_ID == id);
if (mod.IsAccessible()) {
return View(mod);
}
return noRights();
}
I think this works pretty neat :)
精彩评论