简体   繁体   中英

Asp.NET C# Session Variables from class to handler

I am trying, to avoid using querystrings, to use a session variable to pass the desired value. I'm doing this from a class to a handler.

In the class I use:

HttpContext.Session["name"] = "Value";

In the handler I use:

var name = context.Session["name"];

I have already added IReadOnlySessionState or IRequiresSessionState but the session variables remain null.

Some help?

I think you are creating new context again. you should use the same session using HttpContext.Current . Try Code Like below and Refer Comments what i have added below.

    string firstName = "Jeff";
    string lastName = "Smith";
    string city = "Seattle";

    // Save to session state in a Web Forms page class.
    Session["FirstName"] = firstName;
    Session["LastName"] = lastName;
    Session["City"] = city;

    // Read from session state in a Web Forms page class.
    firstName = (string)(Session["FirstName"]);
    lastName = (string)(Session["LastName"]);
    city = (string)(Session["City"]);

    // Outside of Web Forms page class, use HttpContext.Current.
    HttpContext context = HttpContext.Current;
    context.Session["FirstName"] = firstName;
    firstName = (string)(context.Session["FirstName"]);

I realize this is an old post, however others may find this useful.

Try passing HttpContext.Current as a parameter to the routine in your common class.

Code from the web forms class:

protected void SetSessionValue()
{
    var CurrentSession = HttpContext.Current;

    oCommonClass.cSetSessionValue(CurrentSession);

    var SessionValue = Session("SessionValue");
}

Code from the common class:

public void cSetSessionValue(object cCurrentSession)
{
    var cSessionValue = "New Value";
    cCurrentSession.Session("SessionValue") = cSessionValue;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM