Web方法中Session变量的奇怪行为

问题描述

请阅读我的问题,它与如何访问网络方法或如何使用会话无关。'

我正面临一个问题,但没有得到。

我有一个sessioninfo类,其中包含所有与会话相关的信息。 当我在Page_load()中使用它时,它工作正常。但是当我尝试在web方法中访问它时,显示给我这样的错误:“ 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变量时,它给我错误(using语句中已经包含了名称空间)

SessionInfo.UserID  //this want work.

当我将其与命名空间配合使用时,其工作正常。

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

解决方法

根据您的描述,我假设您在文件顶部缺少“ using”语句。 只需添加“使用Abc.Common;”即可。在文件的第一行,它应该可以正常工作。 哦。它与网络方法无关。这就是名称空间的工作方式。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...