MVC 3 Request.Cookies值无意地动态切换

时间:2012-10-27 13:05:26

标签: asp.net-mvc-3

我的BaseController(MVC 3)中有重定向问题我有两个langage版本的我的网站波兰语和英语(由$.cookie插件设置)。如果设置了英语,用户想要去波兰语网址 - 我想进行正确的重定向。但是,无论何时我在OnActionExecuting方法中进行重定向,在ExecuteCore方法中,我都会看到语言出于某种原因切换 - 请参阅(*)行。

更重要的是,在这种情况下,我获得了OnActionExecutingExecuteCore方法之间的无限重定向。为什么?

public class BaseController : Controller
{
    protected override void ExecuteCore()
    {
        if (Request.Cookies["language"] != null)
        {
            if (Request.Cookies["language"].Value != "pl-PL" && Request.Cookies["language"].Value != "en-US")
                Request.Cookies["language"].Value = "en-US";
        }
        else
            Request.Cookies.Add(new HttpCookie("language", "en-US"));

        Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(Request.Cookies["language"].Value);
        Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;

        base.ExecuteCore();
    }

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        switch (filterContext.ActionDescriptor.ActionName)
        {
            case "Onas":
                if (Request.Cookies["language"].Value == "en-US")
                {
                    filterContext.Result = new RedirectResult("/About", true);
                    return;
                }
                break;
            case "About":
                if (Request.Cookies["language"].Value == "pl-PL")
                {
(*)                 filterContext.Result = new RedirectResult("/Onas", true); // Request.Cookies["language"].Value will be en-US inside the ExecuteCore method - why ?
                    return;
                }
                break;
        }

        base.OnActionExecuting(filterContext);
    }
}

1 个答案:

答案 0 :(得分:0)

检查Cookie路径属性。您可以通过/Onas网址上的en-US和/About网址上的pl-PL获得无限重定向。

确保使用{ path: '/' }

的jQuery插件设置全局Cookie