设置&在Asp.net核心中获取Cookie

时间:2018-01-03 14:28:32

标签: asp.net-core asp.net-core-mvc

使用asp.net core 2.0 mvc c#

我在同一个域中有2个应用程序,即

 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class MyCustomFilter: ActionFilterAttribute
{
   public override void OnActionExecuting(ActionExecutingContext context)
    {
      //Here I want to check my cookie

    }
}

第一个应用程序app1上有一个链接,单击该链接会重定向到我的第二个应用程序app2。

我想将app1中的ID传递给app2。我尝试过querystrings。虽然我已经成功地设置了当重定向从一个页面转到另一个页面时难以维护/传递我的app2中的那些。

所以我想到了使用cookies。 我想要的是当用户点击app1中的链接时设置了cookie,我被重定向到app2,在这里我想检查已设置的cookie。

我想检查actionfilter中的cookie,如下所示:

btn

我尝试使用HttpContext.Response.Cookies.Get,但这不存在。

请指点。 感谢

1 个答案:

答案 0 :(得分:2)

我已经解决了以下问题:

App1的: 在app1中设置查询字符串,如下所示

  <a href="http://localhost?id=abc">Click here </a>

App2的: 从上下文中获取查询字符串,然后根据查询字符串值创建cookie。在后续请求中,我检查创建的cookie。

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class MyCustomFilter: ActionFilterAttribute
{
   public override void OnActionExecuting(ActionExecutingContext context)
    {
      //this is querystring being passed from app1 to my app2 controller
      string id =  userId = filterContext.ActionArguments["id"].ToString();

        //Creating cookie
       filterContext.HttpContext.Response.Cookies.Append("Id", is, new CookieOptions()
                {
                    Expires = DateTime.Now.AddDays(5)
                });

        //Now I can check for this cookie and then proceed or deny acccess
    }
}