Reputation: 445
I'm still learning MVC and have conceptual question about method attributes.
If I see this in code
[SomeAttribute]
public ActionResult Index() {
return View();
}
Does the presence of [SomeAttribute] cause code to be called by the platform or is it simply there as a data structure to be retrieved by some code (a filter, for instance) that would care whether or not it exists?
From what I can tell its the latter but its not clear. I'm using examples for attributes which calls this in Global.asax.cs
GlobalFilters.Filters.Add(new SomeAttribute());
The code gets called for every method, whether or not the attribute is set. Part of me thinks this is by design and part of me thinks I don't grok it yet.
thanks,
john
Upvotes: 0
Views: 44
Reputation: 1224
It may be as some kind of action filter, when the action filter is registered globally then whenever an action is being invoked then the action filter gets executed and performs the operation as intended. The action filter will have two methods OnActionExecuting and OnActionActionExecuted. The first will be invoked upon calling the action method and the second is invoked when the action result is executed. Please refer the following link to create custom action filter.
Upvotes: 1
Reputation: 887413
Attributes by themselves do not run any code.
The MVC action pipeline uses Reflection to look for all filter attributes on the action method and controller class, and manually invokes them, just like it does for the global filter collection.
Upvotes: 2