bilpor
bilpor

Reputation: 3921

Session changes across solution .net Core 2.1

I have a .net core 2.1 solution and in it, it has a wep API project and for the moment a separate MVC front end project using Razor. In both projects startup.cs file I declare services.AddHttpContextAccessor();

From the front end code I set the session to be 1 hour and I can see the value of the HttpContext.Session.Id. So now a call is made to a WebApi Method and I pass an IhttpContextAccessor object, but now when I look at the session.Id on the passed context it doesn't hold the same value as that set by the calling app. Why isn't the context the same?

In my WebApi I have written a custom AuthorisationFiter and it has been placed on one of the api's Methods. I am referencing the context in the following way:

…..
public class AuthorisationFilter : IAuthorizationFilter
    {
        private readonly IHttpContextAccessor _httpContext;
        public AuthorisationFilter(IHttpContextAccessor httpContext) => _httpContext = httpContext;

        public void OnAuthorization(AuthorizationFilterContext context)
        {…….

Upvotes: 0

Views: 135

Answers (1)

matt_lethargic
matt_lethargic

Reputation: 2796

If you have a separate project for the MVC site then you are in fact creating two separate sites running in their own app pools etc. You cannot share Session State between these two, by default session data is stored in-memory for each app. You might be able to setup a shared session store for this, but this sounds like a hack at best and you probably want to look at what you're trying to achieve as there will more than likely be a better way. Further Reading

I'm not sure exactly how you're 'passing' the IHttpContextAccessor object, but this doesn't seem to be a good idea.

These days when creating an API you really want to be making it stateless, using Session State is the exact opposite of this.

Upvotes: 2

Related Questions