mvc 4中未设置Cookie

本文关键字:设置 Cookie mvc | 更新日期: 2023-09-27 18:28:48

我创建了一个授权过滤器

public class LandedAttribute : AuthorizeAttribute
{
   protected override bool AuthorizeCore(HttpContextBase httpContext) {
      if (httpContext == null)
         throw new ArgumentNullException("httpContext");
      if (HttpContext.Current.Response.Cookies["LegalDisclaimer"].Value != "Accepted")
      {
         return false;
      }
      return true;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext){
   string url = filterContext.HttpContext.Request.Url.ToString();
   System.Diagnostics.Debug.WriteLine(url);
   filterContext.Result = new RedirectToRouteResult(
   new RouteValueDictionary {
     { "action", "Index" },
     { "controller", "Landing" },
     { "returnUrl", url }
   });
}

}

和我的着陆控制器

public ActionResult Index(string returnUrl)
        {
            ViewBag.rdParm = returnUrl;
            return View();
        }
        public ActionResult Accept(string returnUrl)
        {
            HttpCookie cookie = new HttpCookie("LegalDisclaimer", "Accepted");
            Response.Cookies.Add(cookie);
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

然后我设置了一个类似的控制器

[Landed] 
public class someController : Controller
{
contoller actions here
}

问题是LegalDisclaimer cookie从未设置,并且总是返回null。这是我第一次尝试在mvc中学习Authorize过滤器,它的3天没有任何进展。有人能帮我调试一下吗?

mvc 4中未设置Cookie

忽略此项-请参阅下面的更新

看起来你永远都无法设置cookie。我想,LandingController中的Accept操作是唯一设置cookie的操作。但是,您永远无法到达那里,因为您创建的自定义授权筛选器(LandedAttribute)会阻止应用程序到达那里(因为未设置cookie)。

您可能想在该操作上添加一个[AllowAnonymous],以允许它通过,从而可以设置cookie。

例如

[AllowAnonymous]
public ActionResult Accept()
{
    // body of the action here.
}

更新

我刚刚意识到您的LandedAttribute正在尝试读取传出的cookie,而不是传入的cookie。

你有HttpContext.Current.Response。使用Request上的cookie,而不是Response

您的控制器操作应该仍然使用响应,因为您正在那里设置传出cookie。