在MVC控制器中读取Cookie

时间:2015-09-26 21:44:20

标签: c# asp.net-mvc cookies asp.net-mvc-5 httpcontext

我正在使用MVC 5.2,我想用控制器方法访问cookie:

public class RestrictedController : Controller
{
    [HttpGet]
    public ActionResult TestMethod()
    {
        HttpCookie myCookie = HttpContext.Request.Cookies["cookieName"] as HttpCookie;
        if (myCookie == null)
        {
           ViewBag.Debug = "Cookie not found";
        }
    }
    return View();
}

到目前为止很直接,但cookie总是为空。我检查了从浏览器发送到应用程序的请求标头,他们确实包含了几个cookie。当我检查HttpContext.Request.Cookies.AllKeys时,我看到根本没有cookie。

所以我试着检查原始请求标题,我找到了这个答案: https://stackoverflow.com/a/12696631

但字符串总是空的?

我也尝试过我在这里找到的解决方案:https://stackoverflow.com/a/1358403 但即使在那里,也无法访问cookie。

我也尝试过System.Web.HttpContext.Current.Request.Cookies.AllKeys - 但也没有。

我无法在IIS Express上的开发计算机上重现此问题(我可以在那里阅读我的Cookie)。这只发生在高效的IIS机器上。

有什么想法吗?

更新

我可以通过Request.ServerVariables访问cookie来找出解决方法,如下所示:

private static string COOKIE_HEADER = "HTTP_COOKIE";
private string GetCookieValueByServerVariables(string cookieName)
{
    if (String.IsNullOrWhiteSpace(Request.ServerVariables[COOKIE_HEADER])) { return null; }
    Dictionary<string, string> cookies = Request.ServerVariables[COOKIE_HEADER]
                                        .Split(';')
                                        .Select(value => value.Split('='))
                                        .ToDictionary(pair => pair[0], pair => pair[1]);            
    return cookies[cookieName];
}

我仍在疑惑,为什么我无法通过Request.Cookies []访问它们。这可能是MVC5中的错误吗?

0 个答案:

没有答案