ASP.NET MVC : Context sensitive validation
I have bunch of action-methods that need to verify the ownership of the orderId
passed to the action something like:
public ActionResult CancelOrder(int orderId) {
If (!MyDatabase.VerifyOwnership(orderId, User.Identity.Name) return View("You are an imposter!");
// ...
}
What's an easy way to verify orderId
belongs to User.IdentityName
without having to copy/paste same lines over and over?
I have tried ActionFilterAttribute
but it doesn't have access to the context (MyDatabase
object for example). What's a go开发者_Go百科od way to handle this?
" but it doesn't have an access to the context"
Sure it does:
public class VerifyOwner : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var myController = (MyControllerType)filterContext.Controller;
if (!myController.MyDatabase.VerifyOwnership(orderId, User.Identity.Name)
//do what you do
base.OnActionExecuting(filterContext);
}
}
All you have to do is cast the Controller property to your controller type. This get really easy is you have a custom base Controller all your Controllers inherit from. Then set that base controller to have the MyDatabase property and you have an easy time using this attribute across multiple controllers.
Your controller seems to have access to your context. Therefore if you use an action filter attribute that implements IAuthorizationFilter
you can cast the filterContext.Controller
in the OnAuthorization
method to your controller type and be able to do what you set out to in the first place. (Which I reckon is the way to go!)
Kindness,
Dan
精彩评论