views:

31

answers:

2

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 good way to handle this?

+1  A: 

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

Daniel Elliott
I was trying to avoid down cast, but I guess it's better than singleton.
One thing to bear in mind ... if you don't use IAuthorizationFilter then another filter on the same method could run before your "you are an imposter!" filter ;)
Daniel Elliott
+1  A: 

" 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.

jfar