Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I update a session after an Ajax call?

My application makes a lot of requests to an API controller. The problem I am running into is that my APIController has no access to the current session (which - it shouldn't). But since the calls are made via javascript after the page loads - I don't know how to tell my app to update the session.

What is the accepted way to handle changes to session values after receiving updated data from an ajax call?

Example:

public static class SessionManager
{
    public static User CurrentUser
    {
        get
        {
            return (User)HttpContext.Current.Session["CurrentUser"];
        }
        set
        {
            HttpContext.Current.Session["CurrentUser"] = value;
        }
    }
}

public class SomeController : ApiController
{
    public HttpResponseMessage DeleteSomething(SomeModel model)
    {
        // Do work
    }
}

then in the view

$.ajax({
     type: 'DELETE',
     url: '{PATH TO API}',
     data: { the data },
     traditional: true,
     success: function (response) {
         // Now I need to update the user stored in the session
         // How do I do that?
     } else {
     }
});
like image 248
drewwyatt Avatar asked Dec 31 '25 17:12

drewwyatt


1 Answers

You are correct. Web API intentionally disables the session because it's a REST-compliant API, and REST is stateless. Frankly, there's no way that I know of to change a value in the session on your MVC side of things from a Web API controller.

But, your AJAX doesn't have to call a Web API, you can just as easily create an MVC controller action that responds to an AJAX request, and you would be able to modify the session from there of course. I think that's going to be your only choice really.

like image 125
Chris Pratt Avatar answered Jan 02 '26 06:01

Chris Pratt