Method of using session in ASHX (get session value) _ Practical Tips

Source: Internet
Author: User
Tags httpcontext

Web development, in general handlers, it is easy to get the request and response objects, such as:

Copy Code code as follows:

HttpRequest _request = context. Request;

HttpResponse _response = context. Response;

But it's not that easy to get the value of the session.

For example, if you want to get the login user information saved in the session in Ashx session["Loginuser"]

If you only use the context. session["Loginuser"] is the exception that will report "an object reference is not set to an instance of an object"!

The following methods are used specifically:

Copy Code code as follows:

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using System.Web.SessionState;

Namespace DtlCalendar.Mobile.Site.Manage
{
<summary>
Summary description of DELAPK
</summary>
public class Delapk:ihttphandler, ireadonlysessionstate
{
Ireadonlysessionstate: Read-only access session
IRequiresSessionState: Read-Write access 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 IDs) && 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;
}
}
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.