Back-End Development

Setting Cookies Globally Across All Controllers in .NET MVC

Istock 636932704 (2)

If you are looking to set the value of the cookies across all the controllers, you can use action filters and apply them on controllers. Action filters contain logic that will be implemented before or after a controller action is executed. They can be applied to an individual action method or the entire controller.

I will give you an overview of how your ActionFilterAttribute class could look like and explain each step along the way. You can find screenshot examples below.

Overview of an ActionFilterAttribute Class

  1. Create a public class named UserCookieFilter that inherits from ActionFilterAttribute
  2. Override the OnActionExecuting method
    • OnActionExecuting method is one of the four overload methods in the ActionFilterAttribute that will be called “before” the controller is called. It takes an ActionExecutingContext as its parameter.
  3. Pass that filter context into the base OnActionExecuting method
  4. Set the default value of the cookie
  5. Create conditions to modify the value of the cookies accordingly
  6. Add the value of the cookie to the filter context
  7. Apply the filter to the controller
Covid 19
COVID-19: Digital Insights For Enterprise Action

Access Perficient’s latest insights into how you can leverage digital technologies to not only respond to the pandemic, but drive your operations forward and deliver experiences your customers need.

Get Informed

Bp12 1

Bp12 2

You can now apply the UserCookieFilter attribute to the controller and your cookies will be passed along to the view.

Bp12 3

You can use the hidden input value if you need the value of the cookie to render some parts of the view using JavaScript.

<input type="hidden" id="buttonInfo" value="@Response.Cookies["adminAccess"].Value" />

    var buttonInfo = document.getElementById('buttonInfo').value;

About the Author

David Hwang is an Associate Technical Consultant in the Sitecore/Microsoft Business Unit. He will be blogging about various concepts in technologies for beginners.

More from this Author

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Subscribe to the Weekly Blog Digest:

Sign Up