【问题标题】:Asp.Net MVC Culture Cookie Changes But Not UI Language Until Second RefreshAsp.Net MVC 文化 Cookie 更改但 UI 语言不会更改,直到第二次刷新
【发布时间】:2017-01-03 19:35:11
【问题描述】:

在我的 Asp.Net MVC 应用程序中,用户来自另一个系统,其 URL 包含他们自己的 UserId。在用户的初始请求中,经过认证过程,将用户的语言选项同步到相应的cookie值。

    [HttpPost]
    [AllowAnonymous]
    public JsonResult Login(Guid userId, UserType userType)
    {
        try
        {
            IAccount account = null;

            if (userType == UserType.SystemUser)
                account = _accountService.CheckSystemUser(userId);
            if (userType == UserType.Employee)
                account = _accountService.CheckEmployee(userId);

            if (account == null) throw new Exception(ErrorMessages.UserNotFound);

            var roles = account.Roles.ToArray();

            var principalModel = new CustomPrincipalViewModel
            {
                UserId = account.UserId.ToString(),
                FullName = account.FullName,
                Roles = roles,
                Language = account.Language
            };

            var userData = JsonConvert.SerializeObject(principalModel);
            var ticket = new FormsAuthenticationTicket(1, principalModel.FullName, DateTime.Now,
                DateTime.Now.AddMinutes(30), false, userData);
            var encryptedTicket = FormsAuthentication.Encrypt(ticket);
            var requestCookie =Request.Cookies[FormsAuthentication.FormsCookieName];
            if (requestCookie != null) requestCookie.Expires = DateTime.Now.AddDays(-1);
            var responseCookie =Response.Cookies[FormsAuthentication.FormsCookieName];
            if(responseCookie != null) responseCookie.Expires = DateTime.Now.AddDays(-1);
            var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            Response.Cookies.Add(cookie);

            SetCulture(account.Language.CultureCode);

            return Json(new {isSuccess = true, userFullName = account.FullName});

        }
        catch (BusinessExceptions.CannotConnectToCrmServiceException ex)
        {
            ElmahManager.Log(ex);
            return Json(new { isSuccess = false, errorText = ErrorMessages.GeneralError });
        }
        catch (Exception exception)
        {
            ElmahManager.Log(exception);
            return Json(new { isSuccess = false, errorText = ErrorMessages.GeneralError });
        }
    }

    private void SetCulture(string culture)
    {
        culture = CultureHelper.GetImplementedCulture(culture);
        var requestCookie =Request.Cookies["_culture"];
        if (requestCookie != null) requestCookie.Expires = DateTime.Now.AddDays(-1);


        var cultureCookie = Request.Cookies["_culture"];
        if (cultureCookie == null)
        {
            cultureCookie = new HttpCookie("_culture")
            {
                Value = culture,
                Expires = DateTime.Now.AddYears(1)
            };
        }
        else
        {
            cultureCookie.Value = culture;
            cultureCookie.Expires = DateTime.Now.AddYears(1);
        }
        Response.Cookies.Add(cultureCookie);
        Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(culture);
        Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
    }

在这个过程之后,当我从数据库中更改用户的语言选择并刷新页面时,页面语言并没有改变。同时,当我检查cookie值时,我看到它与当前的语言值相同,但页面语言不会改变,直到页面被第二次刷新。

【问题讨论】:

  • 你的意思是Login()用户有了默认语言后,刷新后才能得到合适的语言?
  • 为什么会改变? Login 方法的结果是 json(可能由 AJAX 触发) - 因此调用设置文化 cookie 的 Login 方法不会强制页面刷新。
  • 你是对的@MaxMokrousov
  • 正如你所说的 AJAX @OndrejSvejdar 调用的登录方法。如何在这种方法中强制刷新页面?
  • @Yusuf Duyar。使用 ActionResult 代替 JsonResult 返回登录值。

标签: c# asp.net-mvc cookies


【解决方案1】:

你必须改变

public JsonResult Login(Guid userId, UserType userType) 

public ActionResult Login(Guid userId, UserType userType) 

并返回查看或重定向。

[HttpPost]
[AllowAnonymous]
public ActionResult Login(Guid userId, UserType userType)
{
    try{

     //Your logic 
     return View(new {isSuccess = true, userFullName = account.FullName});
    }
    catch (BusinessExceptions.CannotConnectToCrmServiceException ex)
    {
        ElmahManager.Log(ex);
        return View(new { isSuccess = false, errorText = ErrorMessages.GeneralError });
    }
    catch (Exception exception)
    {
        ElmahManager.Log(exception);
        return View(new { isSuccess = false, errorText = ErrorMessages.GeneralError });
    }
}

【讨论】:

  • 我之前的代码就是你说的。然而,客户表示,他们在第一次打开应用程序时等待用户登录的时间太长,并且他们看到一个空白屏幕。之后,我更改了代码,以便我的代码立即返回视图并使用 ajax 查询执行所有其他操作。您如何做到这一点,让用户保持在加载屏幕上并同时使用新语言加载页面?
  • @Yusuf Duyar 我宁愿建议您调查性能问题而不是制作 ajax。但是,如果您想发出 ajax 请求,则必须调用 location.reload();在回调中。
  • 感谢您的解释 :) 我已更改身份验证过程并从此操作返回视图。
猜你喜欢
  • 1970-01-01
  • 2014-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多