Asp.Net MVC5如何确保cookie存在?

Vla*_*and 3 asp.net cookies asp.net-mvc asp.net-mvc-5 asp.net-identity

我是MVC的新手(5)。为了向我的网站添加本地化支持,我向我的网站添加了一个“ 语言 ”字段ApplicationUser : IdentityUser

现在将这些信息存储在浏览器中并确保即使用户手动将其删除也可以重新创建的最佳方法是什么?


TL; 但是我有时间

到目前为止,我一直在尝试:

我开始用我的方法创建一个cookieprivate async Task SignInAsync(ApplicationUser user, bool isPersistent)但我注意到:

  1. 如果用户已经通过身份验证,并且使用.Aspnet.Applicationcookie自动登录,并且我的语言cookie可能同时过期(或被删除),则不使用此方法。

  2. 用户可以出于娱乐目的手动删除cookie。

我考虑过检查它在控制器中的存在(查询登录的用户并从数据库中获取它),它可以工作,但我需要在每个控制器中都进行检查。我不确定执行此操作的正确方法。

关于如何解决此问题并确保应用程序在每个请求上都有有效的“语言cookie”的任何建议?

Jam*_*mes 5

在我看来,您想要的是自定义操作筛选器。您可以覆盖该OnActionExecuting方法,这意味着在调用任何操作之前先运行逻辑

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后全局注册您的属性,这样它就成为每个控制器操作的默认行为

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
    filters.Add(new EnsureLanguagePreferenceAttribute());
}
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢这个,干净又容易。我什至可以检查过滤器名称和身份验证状态 (2认同)