SessionID 在 ASP.NET Core web api 中不断变化
SessionID keeps changing in ASP.NET Core web api
我正在使用 Angular 2 作为前端,Asp.net Core Web API 作为服务器 side.my 问题是当我试图在 [=16] 中维护会话时=] ,但对于每个请求,会话 ID 都在更改并且数据已丢失,知道我想在服务器端管理会话是否可以在网络中维护会话 api 如果没有任何其他方式来维护会话服务器端 ?
TanvirArjel 的这个回答对我有用:ASP.NET core 2.1 session
基本上,在ConfigureServices()方法上,在Startup class中,配置Cookies Policy时,需要将"options.CheckConsentNeeded"定义为false,所以不需要用户同意使用 cookie(有利于开发)。
遵循批准的答案并没有解决我的问题。经过进一步搜索,我遇到了[this post][1],它解释了原因和解决方案。
ASP.NET 会话详细信息依赖于 cookie,而跨域请求对此存在问题。引用上述 post -
XMLHttpRequest from a different domain cannot set cookie values for
their own domain unless withCredentials is set to true before making
the request
Angular
中是如何解决这个问题的
这是我在 Angular
中如何解决这个问题的总结
- 创建一个 [Angular 拦截器][2] 顾名思义
在发送请求之前拦截请求(通过
申请)
- 克隆请求对象
- 添加值为
true
的 withCredentials
属性
它看起来应该与此类似
@Injectable()
export class ConnectInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authReq = req.clone({
headers: req.headers.set("Authorization", "custom-token"),
withCredentials: true // Important for consistent session id in ASP.NET
});
return next.handle(authReq);
}
}
希望这对您有所帮助
[1]: https://www.blinkingcaret.com/2018/07/18/secure-an-asp-net-core-web-api-using-cookies/
[2]: https://angular.io/api/common/http/HttpInterceptor
或者您只需要为会话设置一些值。 Id 将保留。
HttpContext.Session.SetString("Something", "Something");
我正在使用 Angular 2 作为前端,Asp.net Core Web API 作为服务器 side.my 问题是当我试图在 [=16] 中维护会话时=] ,但对于每个请求,会话 ID 都在更改并且数据已丢失,知道我想在服务器端管理会话是否可以在网络中维护会话 api 如果没有任何其他方式来维护会话服务器端 ?
TanvirArjel 的这个回答对我有用:ASP.NET core 2.1 session
基本上,在ConfigureServices()方法上,在Startup class中,配置Cookies Policy时,需要将"options.CheckConsentNeeded"定义为false,所以不需要用户同意使用 cookie(有利于开发)。
遵循批准的答案并没有解决我的问题。经过进一步搜索,我遇到了[this post][1],它解释了原因和解决方案。
ASP.NET 会话详细信息依赖于 cookie,而跨域请求对此存在问题。引用上述 post -
XMLHttpRequest from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request
Angular
中是如何解决这个问题的这是我在 Angular
中如何解决这个问题的总结- 创建一个 [Angular 拦截器][2] 顾名思义 在发送请求之前拦截请求(通过 申请)
- 克隆请求对象
- 添加值为
true
的
withCredentials
属性
它看起来应该与此类似
@Injectable()
export class ConnectInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authReq = req.clone({
headers: req.headers.set("Authorization", "custom-token"),
withCredentials: true // Important for consistent session id in ASP.NET
});
return next.handle(authReq);
}
}
希望这对您有所帮助 [1]: https://www.blinkingcaret.com/2018/07/18/secure-an-asp-net-core-web-api-using-cookies/ [2]: https://angular.io/api/common/http/HttpInterceptor
或者您只需要为会话设置一些值。 Id 将保留。
HttpContext.Session.SetString("Something", "Something");