I have a session variable that I need to use on a cs page with many webmethod functions. If I declare it as follows I don't always get the latest variable. Sometimes it gives me the variable that was stored before the last one. What am I doing wrong?
public partial class uc_functions : MyBasePage
{
static string ucService = HttpContext.Current.Session["ucService"] as string;
....
[WebMethod] //1
[WebMethod] //2
[WebMethod] //3
Currently you're initializing the variable once, when the class is first loaded. You want to have a different value on each request.
Rather than having a variable for that, you should have a property or method. For example:
private static string Service
{
get { return (string) HttpContext.Current.Session["ucService"]; }
}
Or in C# 6:
private static string Service => (string) HttpContext.Current.Session["ucService"];
(As an aside, I'd review the .NET naming conventions - a class called uc_functions
makes me shudder...)
See more on this question at Stackoverflow