【问题标题】:Set & Get Cookies in Asp.net core在 Asp.net 核心中设置和获取 Cookie
【发布时间】:2018-01-03 23:48:20
【问题描述】:

使用asp.net core 2.0 mvc c#

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

www.mydomain.com/app1 
www.mydomain.com/app2 

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

我想将一个 ID 从 app1 传递给 app2。我试过查询字符串。虽然我成功地设置了当重定向从一个页面到另一个页面时很难在我的 app2 中维护/传递这些内容。

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

我想检查actionfilter中的cookie如下:

 [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

    }
}

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

请指点。 谢谢

【问题讨论】:

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


    【解决方案1】:

    我已经解决了这个问题:

    应用程序1: 在 app1 中设置查询字符串如下

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

    应用程序2: 从上下文中获取查询字符串,然后根据查询字符串值创建 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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-22
      • 2014-04-18
      • 2015-04-24
      • 2017-07-27
      • 2020-04-20
      • 1970-01-01
      • 1970-01-01
      • 2021-07-13
      相关资源
      最近更新 更多