簡體   English   中英

Web方法中Session變量的奇怪行為

[英]Strange behavior of Session variable in web method

請閱讀我的問題,它與如何訪問 webmethod 或如何使用 session 無關。

我正面臨一個問題,但沒有得到解決。

我有一個 sessioninfo 類,其中包含所有與會話相關的信息。 當我在 Page_load() 中使用它時,它工作正常。但是當我嘗試在 webmethod 中訪問它時,它會顯示如下錯誤:“SessionInfo.UserId 錯誤 CS0103:當前上下文中不存在名稱‘SessionInfo’ ”

這是我的代碼 SessionInfo 類

namespace Abc.Common
{
      public class SessionInfo
      {
          public static decimal UserID
          {
             get
             {
                 try
                 {
                    if (HttpContext.Current.Session["UserID"] != null)
                       return Convert.ToDecimal(HttpContext.Current.Session["UserID"]);
                    return 0;
                 }
                 catch (Exception)
                 {
                    return 0;
                 }
             }
             set
             {
                 HttpContext.Current.Session["UserID"] = value;
             }
         }
         ...
         ...
      }
  }

//asp.net后端代碼(.aspx.cs)

using Abc.common;
....

Page_Load 中的代碼

protected void Page_Load(object sender, EventArgs e)
{
    if (SessionInfo.UserID == 0)    //here its working fine
    {
        Response.Redirect(Page.ResolveUrl("~/Default.aspx?errormsg=Your Session Is Expired."));
    }
    if (!IsPostBack)
    {
        ...
    }
}

Web方法代碼

[System.Web.Services.WebMethod]
public static DataTable ValidateUploadedFiles()
{
     //if (Abc.Common.SessionInfo.UserID == 0)    //its working fine
     if (SessionInfo.UserID == 0)
     {
         ...
     }
}

當我直接使用 sessioninfo 變量時,它給了我錯誤(使用語句中已經包含命名空間)

SessionInfo.UserID  //this want work.

當我將其與命名空間一起使用時,它的類工作正常。

Abc.Common.SessionInfo.UserID  //this is working fine.

根據您的描述,我假設您在文件頂部缺少“使用”語句。 只需添加“使用 Abc.Common;” 在文件的第一行,它應該可以正常工作。 哦。 它與 webmethod 無關。 這就是命名空間的工作方式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM