【发布时间】:2020-10-28 22:52:23
【问题描述】:
我目前正在做一个项目,使用 .Net Core 3.1 作为服务器,使用 Angular 作为客户端。
我正在使用 .net 核心会话将我的值存储在会话中,现在当我使用邮递员发送发布请求时,我可以在 Cookies 选项卡下看到响应发回给我的键(名称为 .AspNetCore.Session),同样,当我从客户端发送请求时,我在网络选项卡中看到响应标头下的理想响应,但是当我尝试将其作为可观察对象返回时,它返回为空。
现在我的问题是如何从客户端访问该 set-cookie?我尝试了一些方法,没有一个是好的。
我当前的 startup.cs 配置服务:
{
services.AddControllers().AddNewtonsoftJson(options => options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);
services.AddCors();
services.AddDistributedMemoryCache();
services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.IgnoreNullValues = true;
});
services.AddHttpContextAccessor();
services.AddScoped<IFavoriteRepository, FavoriteRepository>();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(1800);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
}
会话方法
public void AddRepo(Repository repo)
{
var repository = new Repository() { RepoName = repo.RepoName, AvatarUrl = repo.AvatarUrl };
var json = JsonConvert.SerializeObject(repository);
_httpContextAccessor.HttpContext.Session.SetString("SessionUser", json);
}
public Repository GetRepo()
{
var sessionUser = JsonConvert.DeserializeObject<Repository>(_httpContextAccessor.HttpContext.Session.GetString("SessionUser"));
return sessionUser;
}
控制器:
[HttpPost]
public IActionResult AddFavorite(Repository repo)
{
_repo.AddRepo(repo);
return Ok();
}
角度服务
saveRepo(repo: Repository) {
return this.http.post<any>(this.baseUrl + "Repositories", repo ,{ observe: 'response'})
.pipe(
map(response => {
return response.headers;
})).subscribe(data => console.log(data));
}
【问题讨论】:
标签: .net angular typescript asp.net-core