Home A new session is being created in every request on web api
Reply: 0

A new session is being created in every request on web api

user2927 Published in April 24, 2018, 8:38 am

I am developing a ASPN.NET WEB API 1(with .NET framework 4.0) application with AngularJS, and I am using session to authenticate the users(I know it should be stateless, but for legacy purpose I am using session). In my application, in every request I make to my WEB API it creates a new session, even when I set values to my session.

The sessions is allowed in my appication through this code in Global.asax:

protected void Application_BeginRequest(object sender, EventArgs e)

            string origins = ConfigurationManager.AppSettings["cors-origins"];
            bool hasSlash = origins.Substring(origins.Length - 1, 1) == "/";
            if (hasSlash)
                origins = origins.Substring(0, origins.Length - 1);

            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", origins);
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
                             "GET, POST, PUT, DELETE");
                             "Content-Type, Accept");

        protected void Application_PostAuthorizeRequest()
            if (IsWebApiRequest())

Then I set values to my session in my controller:

public HttpResponseMessage Post(LoginViewModel model)

        FormsAuthentication.SetAuthCookie(model.User, false);
        HttpContext.Current.Session["usuario"] = model.User;
        return Request.CreateResponse(HttpStatusCode.Accepted, "User successfylly logged in!");

But when I do another request to my application to access another method in controller, it throws me an error because session is null, like in this method:

 public HttpResponseMessage Get()
        var userName = HttpContext.Current.Session["usuario"];

        return Request.CreateResponse(HttpStatusCode.Accepted, userName);

In my web.config, session is configured like this:

 <sessionState mode="InProc" customProvider="DefaultSessionProvider" >
        <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />

PS: It does not work on Chrome, but on IE it works, and doing request directly on postman it also works.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.304185 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO