Set Session in Web API using jQuery Ajax in ASP.Net

Last Reply 10 days ago By dharmendr

Posted 10 days ago

I have face a problem.

I want to set session in web api with jquery ajax request without using asp.net mvc.

Please  help me.

 

You are viewing reply posted by: dharmendr 10 days ago.
Posted 10 days ago

Hi aspsun11,

Add Application_PostAuthorizeRequest in global.asax to access Session in Web API controller.

Check the below example.

global.asax

public class Global : HttpApplication
{
    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        GlobalConfiguration.Configure(WebApiConfig.Register);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

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

API Controller

public class SessionController : ApiController
{
    [HttpPost]
    public string SetSession()
    {
        System.Web.HttpContext.Current.Session["Time"] = DateTime.Now;
        return System.Web.HttpContext.Current.Session["Time"].ToString();
    }
}

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.10.2.js"></script>
    <script>
        $(document).ready(function () {
            $("#Save").click(function () {
                $.ajax({
                    url: 'http://localhost:3117/api/Session/SetSession',
                    type: 'POST',
                    dataType: 'json',
                    data: {},
                    success: function (data) {
                       document.write(data);
                    },
                    error: function (xhr) {
                    }
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <input type="button" id="Save" value="Save" />
    </form>
</body>
</html>

Output

09-08-2019 00:19:20