华域联盟 .Net ashx中使用session的方法(获取session值)

ashx中使用session的方法(获取session值)

WEB开发,在一般处理程序中,很容易得到 Request和Response对象,如:

复制代码 代码如下:

HttpRequest _request = context.Request;

HttpResponse _response = context.Response;

但是要得到 Session的值就没有那么简单了。

比如如果要在ashx得到保存在Session中的登录用户信息 Session["LoginUser"]

如果仅仅使用 context.Session["LoginUser"] 的话,是会报 “未将对象引用设置到对象的实例”的异常!

具体要使用下列方法:

复制代码 代码如下:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.SessionState;

namespace DtlCalendar.Mobile.Site.Manage
{
    /// <summary>
    /// DelApk 的摘要说明
    /// </summary>
    public class DelApk : IHttpHandler, IReadOnlySessionState
    {
        // IReadOnlySessionState :只读访问Session
        // IRequiresSessionState :读写访问Session
        public void ProcessRequest(HttpContext context)
        {
            string strID = context.Request["id"];
            context.Response.Clear();
            context.Response.ContentType = "text/plain";
            int id;
            string user;
            if (int.TryParse(strID, out id) && IsLoged(context, out user))
            {
                string reslt = DataProvider.MobileDataProvider.CreateInstance().DelMApk(id).ToString();
                BLL.LogOprHelper.Instance.InsertMLog(user, BLL.LogOpr.Delete, "DelApk result:" + reslt);
                context.Response.Write(reslt);
            }
            else
            {
                BLL.LogOprHelper.Instance.InsertMLog(strID, BLL.LogOpr.Delete, "DelApk result:-1");
                context.Response.Write("-1");
            }
        }

        private bool IsLoged(HttpContext context, out string user)
        {
            BLL.User _User;
            if (context.Session["LoginUser"] != null)
            {
                _User = context.Session["LoginUser"] as BLL.User;
                if (_User != null)
                {
                    user = _User.Account;
                    return true;
                }
            }
            user = string.Empty;
            return false;
        }

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    }
}

您可能感兴趣的文章:

  • ASP.NET ASHX中获得Session的方法
  • Asp.net在ashx文件中处理Session问题解决方法
  • 在ashx文件中使用session的解决思路
  • ashx介绍以及ashx文件与aspx文件之间的区别
  • ashx文件的使用小结
  • aspx与ascx,ashx的用法总结
  • 后缀为 ashx 与 axd 的文件区别浅析
  • 基于.NET中:自动将请求参数绑定到ASPX、ASHX和MVC的方法(菜鸟必看)
  • *.ashx文件不能访问Session值的解决方法

本文由 华域联盟 原创撰写:华域联盟 » ashx中使用session的方法(获取session值)

转载请保留出处和原文链接:https://www.cnhackhy.com/53102.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部