C# 如何访问AuthorizeAttribute中具有域的cookie

C# 如何访问AuthorizeAttribute中具有域的cookie,c#,asp.net-mvc,cookies,attributes,C#,Asp.net Mvc,Cookies,Attributes,我有以下特点 public class SSOAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { var cookie = httpContext.Request.Cookies["testcookie"]; if (cookie == null) {

我有以下特点

  public class SSOAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var cookie = httpContext.Request.Cookies["testcookie"];
        if (cookie == null)
        {
            Debug.WriteLine("cookie does not exist in attribute");
            cookie = new HttpCookie("testcookie")
            {
                Value = "test",
                Domain = "someotherdomain"
            };
            httpContext.Response.Cookies.Add(cookie);
        }
        else
            Debug.WriteLine("cookie exists in attribute");
        return true;
    }
}
以及以下控制器(MVC 5.0)

当我运行这个测试应用程序时,输出是

属性中不存在cookie

索引中存在cookie

属性中不存在cookie

cookie以秒形式存在


没有域名,一切都很好。该属性在第二次传递时按预期查找cookie。但是,一旦我添加了域,当搜索cookie时,该属性将返回null。它在控制器中仍然显示得很好。有人能解释一下为什么会这样,以及我如何在属性中看到这个cookie吗?

在属性中看不到cookie的原因是因为它是为不同的域设置的,所以浏览器甚至没有随请求一起发送它。在发出请求时尝试运行;您应该看到,您在其他域上设置的cookie不包括在您发出的请求中


尽管如此,您每次都在控制器中看到cookie的原因是,您每次都在属性中设置cookie,而最初没有找到cookie,因为属性在命中控制器之前运行。将cookie值设置为变量,比如
DateTime.Now.ToString()
,然后打印出来调试,看看我的意思。

是的,在继续研究和思考之后,我意识到这就是问题所在。当手动创建cookie时,它会显示出来。但是,一旦浏览器启动下一个调用,由于域的原因,cookie就不包括在内。谢谢你的回复。
  [SSO]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        var cookie = HttpContext.Request.Cookies["testcookie"];
        if (cookie == null)
            Debug.WriteLine("cookie does not exist in Index");
        else
            Debug.WriteLine("cookie exists in Index");

        return RedirectToAction("Second");
    }

    public ActionResult Second()
    {
        var cookie = HttpContext.Request.Cookies["testcookie"];
        if (cookie == null)
            Debug.WriteLine("cookie does not exist in Second");
        else
            Debug.WriteLine("cookie exists in Second");

        return View("Index");
    }
}