Glo*_*ria 2 c# asp.net session-variables code-behind webmethod
我有一个会话变量,我需要在具有许多webmethod函数的cs页面上使用.如果我声明如下,我并不总是得到最新的变量.有时它会给我在最后一个之前存储的变量.我究竟做错了什么?
public partial class uc_functions : MyBasePage
{
static string ucService = HttpContext.Current.Session["ucService"] as string;
....
[WebMethod] //1
[WebMethod] //2
[WebMethod] //3
Run Code Online (Sandbox Code Playgroud)
当前首次加载类时,您正在初始化变量一次.您希望每个请求具有不同的值.
您应该拥有属性或方法,而不是拥有变量.例如:
private static string Service
{
get { return (string) HttpContext.Current.Session["ucService"]; }
}
Run Code Online (Sandbox Code Playgroud)
或者在C#6中:
private static string Service => (string) HttpContext.Current.Session["ucService"];
Run Code Online (Sandbox Code Playgroud)
(顺便说一下,我会回顾一下.NET命名约定 - 一个叫做uc_functions让我不寒而栗的课......)