I am using Angular 2 as front end and Asp.net Core Web API as server side.my problem is when i am trying to maintain session in HttpContext.Session ,But for every request the Session Id is Changing and the data has been lost,Know i want to Manage session in server side Is it possible to maintain session in web api if not any other way to maintain session in server side ?
-
Possible duplicate of [Accessing Session Using ASP.NET Web API](https://stackoverflow.com/questions/9594229/accessing-session-using-asp-net-web-api) – Dec 26 '17 at 18:50
-
I am already familier for Asp.net But the configuration is different for Asp.net Core. I m asking for Asp.net core web api session – JRA Dec 27 '17 at 03:58
3 Answers
This answer from TanvirArjel worked for me: ASP.NET core 2.1 session
Basically, on the ConfigureServices() method, in the Startup class, when you configure the Cookies Policy, you need to define "options.CheckConsentNeeded" as false, so it doesn't requires the user consent to use cookies (good for development).

- 216
- 3
- 6
Following the approved answer did not solve my problem. Upon further search, i came across [this post][1] which explained the reason and a solution.
ASP.NET session details are dependent on cookies and cross domain requests have a problem with just that. Quoting from the aforementioned post -
XMLHttpRequest from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request
How this was addressed in Angular
Here is the summary of how i solved this in Angular
- Create an [Angular Interceptor][2] which as the name suggests intercepts the requests before they are sent (across the application)
- Clone the request object
- Add the
withCredentials
property with the valuetrue
It should look something similar to this
@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);
}
}
Hope this helps [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

- 3,569
- 2
- 34
- 39
Or you only need set some value to the session. The Id will stay.
HttpContext.Session.SetString("Something", "Something");

- 426
- 7
- 16