Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access Session in .ashx file?

Tags:

c#

I want to access some value(which is already set in.aspx file) in .ashx file. I tried to get that value using querystring, session etc but each time it failed. Can anyone suggest me how can we access session value in .ashx file?

like image 762
Kashif Hanif Avatar asked Jul 12 '12 07:07

Kashif Hanif


People also ask

Can we use session in ASPX page?

You can't, JavasSript is used for client side scripting on the browser, and cannot access a Session object from a server.

How can use session handler in asp net?

Step 1: Open Visual Studio 2010. Step 2: Then Click on "New Project" -> "WEB" -> "ASP.NET Empty Web Application". Step 3: Now click on Solution Explorer. Step 4: Now right-click on the "Add" -> "New Item" -> "Web Form" and add the name of the web form and I had added 2 Web Form1.


2 Answers

In the ashx.cs file, also "implement" the interface System.Web.SessionState.IReadOnlySessionState or System.Web.SessionState.IRequiresSessionState.

You don't have to implement any method, just the presence of this makes the Session available (in readonly or read/write mode), through context.Session.

The header would look like:

public class MyHandler: IHttpHandler, System.Web.SessionState.IReadOnlySessionState
like image 135
Hans Kesting Avatar answered Oct 06 '22 01:10

Hans Kesting


In aspx file:

Session.Add("filename", "Test.txt");


After you have set session value in aspx file. Use following to get the value in ashx file.

In ashx file:

public class ImageHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
    public void ProcessRequest(HttpContext context)
    {
      string Name = "";
      if (context.Session["filename"] != null)
         Name = context.Session["filename"].ToString();
    }
}
like image 26
mrd Avatar answered Oct 06 '22 01:10

mrd