我使用角度js,Web API和.net,
尝试通过WebApi设置cookie,这取得了成功。现在我需要在角度js控制器上读取该cookie。我尝试了以下代码,
(function () {
var controllerId = 'app.views.layout.header';
angular.module('app').controller(controllerId, [
'$scope', '$cookies', function ($scope, $cookies) {
var vm = this;
//#region check whether logged in or not
var favoriteCookie = $cookies.get('session-id');
console.log(favoriteCookie)
//#endregion
}]);
})();
在此处,控制台始终为undefined
。
api代码如下,
[HttpPost]
public HttpResponseMessage Post()
{
var resp = new HttpResponseMessage();
var _UserInfoCookies = new NameValueCollection();
_UserInfoCookies["UserId"] = "1";
_UserInfoCookies["UserName"] = "test";
var cookie = new CookieHeaderValue("session-id", _UserInfoCookies);
cookie.Expires = DateTimeOffset.Now.AddDays(1);
cookie.Domain = Request.RequestUri.Host;
cookie.Path = "/";
resp.Headers.AddCookies(new CookieHeaderValue[] { cookie });
return resp;
}
我已经在浏览器上仔细检查了cookie,它存在于那里..
任何人都可以帮我找出我无法读取Cookie的问题吗?
答案 0 :(得分:0)
以下代码将有助于添加Cookie
[HttpPost]
public HttpResponseMessage Post()
{
HttpCookie SenderBranchcookie = new HttpCookie("session-id");
SenderBranchcookie["status"] = "TokenExpired";
SenderBranchcookie["id"] = userId.ToString();
SenderBranchcookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(SenderBranchcookie); // Response = HttpResponseBase
}