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

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

William
1#
William Published in 2017-12-18 12:32:52Z

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")
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods",
                             "GET, POST, PUT, DELETE");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers",
                             "Content-Type, Accept");
                HttpContext.Current.Response.End();
            }
        }

        protected void Application_PostAuthorizeRequest()
        {
            if (IsWebApiRequest())
            {
                HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
            }
        }

Then I set values to my session in my controller:

public HttpResponseMessage Post(LoginViewModel model)
    {
    // SOME BUSINESS LOGIC HERE...

        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" >
      <providers>
        <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
      </providers>
    </sessionState>

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

William
2#
William Reply to 2017-12-18 13:58:31Z

It was missing this line in my Application_BeginRequest

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");

And in every request on AngularJS I should pass withCredentials parameter as true. To achieve that, I put this line on my config file in AngularJS:

$httpProvider.defaults.withCredentials = true;
You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO