Set Session Timeout in Web API Controller in ASP.Net

Last Reply 2 months ago By dharmendr

Posted 2 months ago

In this code you set session. My problem how to expire your session value. Please solve my query. I will try but not run.

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);
    }
}
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 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>

 

You are viewing reply posted by: dharmendr 2 months ago.
Posted 2 months ago
aspsun11 says:
[HttpPost]
    public string SetSession()
    {
        System.Web.HttpContext.Current.Session["Time"] = DateTime.Now;
        return System.Web.HttpContext.Current.Session["Time"].ToString();
    }

Change the above code with below.

[HttpPost]
public string SetSession()
{
    System.Web.HttpContext.Current.Session["Time"] = DateTime.Now;
    System.Web.HttpContext.Current.Session.Timeout = 1; // In minutes.
    return System.Web.HttpContext.Current.Session["Time"].ToString();
}

Refer below link for details.

Session.Timeout