简体   繁体   English

如何在 Angular2 端读取 cookie(由 c# 服务器设置)

[英]How to read cookie on Angular2 side (set by the c# server)

I can't figure out how the angular code can read the cookie set on the server side.我不知道 angular 代码如何读取服务器端设置的 cookie。 The code below is taken from GitHub.下面的代码取自 GitHub。 The function below in written in c# and sets the cookie in Response object by the last line of code.下面的 function 写在 c# 中,并通过最后一行代码在 Response object 中设置 cookie。 My question is how do I read this cookie on the Angular2 java script side.我的问题是如何在 Angular2 java 脚本端读取这个 cookie。 Can someone point me to the right direction please?有人可以指出我正确的方向吗?

private void setTokenCookie(string token)
{
    var cookieOptions = new CookieOptions
    {
        HttpOnly = true,
        Expires = DateTime.UtcNow.AddDays(7)
    };
    Response.Cookies.Append("refreshToken", token, cookieOptions);
}

Angular does not have native support for Cookies . Angular没有对Cookies的本机支持。 You need to use either a built-in library for this available on NPM or deal with it simply with JavaScript and browser capability.您需要使用NPM上可用的内置库,或者只需使用JavaScript和浏览器功能来处理它。

Option 1:选项1:

You can use angular2-cookie您可以使用angular2-cookie

Option 2:选项 2:

You can use a method like this (or update it) to meet your need of reading a cookie:您可以使用这样的方法(或更新它)来满足您读取 cookie 的需要:

readCookies(){
 let name = name + "="; 
 let cookie_array = document.cookie.split(';'),
 for(var i=0;i<cookie_array.length;i++) {
    let cookie=cookie_array[i];
    while(cookie.charAt(0)==' '){
       cookie = cookie.substring(1,cookie.length);
       if(cookie.indexOf(name)==0){
       return cookie.substring(name.length,cookie.length);
      }
   }
 }
}

I hope this helps point you in the right direction.我希望这有助于为您指明正确的方向。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM