1

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?

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

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 ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.