Drazen Bjelovuk Drazen Bjelovuk - 3 months ago 11
ASP.NET (C#) Question

Where is a good place to put common business logic that should run on every view?

I have a project in which I need to check for and add a cookie, regardless of which view the user is currently on. I can place the code inside of the

_Layout
partial view within a code block, but I have doubts that's the conventional place for it. Where should it go?

Answer

View is generally wrong place to put logic.

Action filter is one possible way to centralize the code and allow easy customization, especially for something that sound so close to behavior of AuthorizeAttribute filter.

See Action Filtering in ASP.Net MVC for information.

public class MyCookieFilter : ActionFilterAttribute ...

[MyCookieFilter]
public ActionResult Index()
{
    // The action method logic.
}

Side note: when searching for documentation be carefull to distinguish MVC and WebAPI classes - many have similar names and similar behavior, but can cause some confusion when applied to wrong objects.