asp.net - Prevent users from changing the parameter ID in the Edit action method -
so url on edit/details method looks http://localhost:1234/movies/edit?id=3. if db table contains records belongs else 1, 2, 4, 5, 6. there nothing stopping user directly typing , accessing record 6 (eg /movie/edit/6).
how can prevent happening?
// get: /movie/edit/id public actionresult edit(int id = 0) { movie movie = db.movies.find(id); if (movie == null) { return httpnotfound(); } return view(movie); } // // post: /movie/edit/id [httppost] public actionresult edit(movie movie) { if (modelstate.isvalid) { db.entry(movie).state = entitystate.modified; db.savechanges(); return redirecttoaction("index"); } return view(movie); }
well depends want restrict , want them restrict editing privileges, i'm going give generic answer. can request authorization each of methods or entire class. can give authorization in general registered users or users particular role using [authorize]
generic authorization(must registered , signed in):
// get: /movie/edit/id [authorize] public actionresult edit(int id = 0) { movie movie = db.movies.find(id); if (movie == null) { return httpnotfound(); } return view(movie); } //post: /movie/edit/id [httppost] [authorize] public actionresult edit(movie movie) { if (modelstate.isvalid) { db.entry(movie).state = entitystate.modified; db.savechanges(); return redirecttoaction("index"); } return view(movie); }
authorization based on roll (you can set user lets 'admin' role can access these methods):
// get: /movie/edit/id [authorize(role="admin")] public actionresult edit(int id = 0) { movie movie = db.movies.find(id); if (movie == null) { return httpnotfound(); } return view(movie); } //post: /movie/edit/id [httppost] [authorize(role="admin")] public actionresult edit(movie movie) { if (modelstate.isvalid) { db.entry(movie).state = entitystate.modified; db.savechanges(); return redirecttoaction("index"); } return view(movie); }
Comments
Post a Comment