繁体   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