声明一个将被许多WebMethod函数使用的静态变量



我有一个会话变量,我需要在cs页面上使用许多webmethod函数。如果我像下面这样声明它,我并不总是得到最新的变量。有时它会给出在最后一个变量之前存储的变量。我做错了什么?

public partial class uc_functions : MyBasePage
{
    static string ucService = HttpContext.Current.Session["ucService"] as string;
....
[WebMethod] //1
[WebMethod] //2
[WebMethod] //3

当前,当类第一次加载时,您将初始化变量一次。您希望对每个请求使用不同的值。

与其使用变量,不如使用属性或方法。例如:

private static string Service
{
    get { return (string) HttpContext.Current.Session["ucService"]; }
}

或者c# 6中的

private static string Service => (string) HttpContext.Current.Session["ucService"];

(顺便说一下,我要回顾一下。net的命名约定——一个名为uc_functions的类让我不寒而栗……)

最新更新