2015-05-14 58 views
2

我有一個會話變量,需要在具有許多webmethod函數的cs頁面上使用。如果我聲明如下,我並不總是得到最新的變量。有時它給了我最後一個之前存儲的變量。我究竟做錯了什麼?聲明一個將被許多WebMethod函數使用的靜態變量

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

[WebMethod] //1 
[WebMethod] //2 
[WebMethod] //3 
+0

您需要在每個webmethod中獲取此值,因爲其值可能已更改。 – Mairaj

+0

這是否意味着我必須申報20次?這對我來說沒有意義....!或者也許就是這樣。 – Gloria

+0

沒有聲明它只是一次,並在每個webmethod – Mairaj

回答

7

您目前初始化變量一次,當首次加載的類。您希望每個請求具有不同的值。

而不是有一個變量,你應該有一個屬性或方法。例如:

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

或者在C#6:

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

(順便說一句,我會檢討.NET naming conventions - 一個名爲uc_functions類讓我不寒而慄...)

+0

爲它分配值另外一個命名約定 –

+0

它現在運行良好現在喬恩.....我刪除了下劃線,謝謝。 – Gloria