sensei
sensei

Reputation: 7562

.Net MVC When to use OnActionExecuting?

Some very basic question.

When to initialize or assign in OnActionExecuting?

Very simple scenario:

public partial class OrderController : DefaultController
{
    private int customerId = 0;

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        customerId = WebSecurity.CurrentUserId;

        base.OnActionExecuting(filterContext);
    }
}

Should I assign customerId in OnActionExecuting so I can reuse it in code in each action?

or should I just assign it in separate actions each time?

Upvotes: 0

Views: 2002

Answers (1)

Faust
Faust

Reputation: 15404

the answer is, of course, it depends on your team's coding style and other circumstances.

Another option you haven't considered is creating a custom action filter to contain this logic, and reuse it with only one line of code above the action-method signature.

Then if you decide to apply it to all/any action-methods, you can apply it to the controller, or to a base-controller even.

Upvotes: 1

Related Questions