JRA
JRA

Reputation: 487

SessionID keeps changing in ASP.NET Core web api

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 ?

Upvotes: 3

Views: 8552

Answers (3)

James Poulose
James Poulose

Reputation: 3833

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

  1. Create an [Angular Interceptor][2] which as the name suggests intercepts the requests before they are sent (across the application)
  2. Clone the request object
  3. Add the withCredentials property with the value true

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

Upvotes: 4

thanh
thanh

Reputation: 462

Or you only need set some value to the session. The Id will stay.

HttpContext.Session.SetString("Something", "Something");

Upvotes: 5

Fernando Wolff
Fernando Wolff

Reputation: 216

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).

Upvotes: 4

Related Questions