Asp.Net MVC5 How to ensure that a cookie exists?
asp.net, asp.net-identity, asp.net-mvc, asp.net-mvc-5, cookies
Solution
It sounds to me like what you want here is a Custom Action Filter. You can override the `OnActionExecuting` method which means the logic is run before any action is called
public class EnsureLanguagePreferenceAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var langCookie = filterContext.HttpContext.Request.Cookies["LanguagePref"];
if (langCookie == null)
{
// cookie doesn't exist, either pull preferred lang from user profile
// or just setup a cookie with the default language
langCookie = new HttpCookie("LanguagePref", "en-gb");
filterContext.HttpContext.Request.Cookies.Add(langCookie);
}
// do something with langCookie
base.OnActionExecuting(filterContext);
}
}
Then register your attribute globally so it just becomes the default behaviour on every controller action
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new EnsureLanguagePreferenceAttribute());
}
Problem
I'm new to MVC (5). In order to add localization support to my website I added a "Language" field to my `ApplicationUser : IdentityUser` What's the best approach to now store this information in the browser and ensure that it gets re-created even if the user manually deletes it? TL; but I've got time What I've tried until now: I started creating a cookie in my method `private async Task SignInAsync(ApplicationUser user, bool isPersistent)` but I notice that: This method is not used if the user is already authenticated and automatically logs in using the .Aspnet.Applicationcookie and my language cookie could be meanwhile expired (or been deleted). A user could manually delete the cookie, just for fun. I thought about checking its existence in the controller (querying the logged user and getting it from the db) and it works but I'd need to do it in EVERY controller. I'm not sure is the correct way to do this. Any suggestion about how to approach this problem and guarantee that the application has a valid "language cookie" on every request?