Search code examples
c#asp.netwebformsgeneric-handler

Get value of variable from .aspx.cs in Webhandler.ashx file


I am trying to accept files for upload through the httphandler and I need the path I have coming from a drop down list in the .aspx. I have the path as a variable in the aspx.cs file but I can't access it in the .ashx file. I think it has to do with the web.config file I added reference for the .ashx to the system.web configuration but no change.

'<%@ WebHandler Language="C#" Class="FileHandler" %>'

using System;
using System.Web;

public class FileHandler : IHttpHandler {

public void ProcessRequest (HttpContext context) {
    if (context.Request.Files.Count > 0)
    {
        HttpFileCollection files = context.Request.Files;

        foreach(string key in files)
        {
            HttpPostedFile file = files[key];
            string fileName = context.Server.MapPath("thisIsWhereINeedThePath" + key);

            file.SaveAs(fileName);

        }
        context.Response.ContentType = "text/plain";
        context.Response.Write("Great");

    }
}

public bool IsReusable {
    get {
        return false;
    }
 }

}

I tried to pass the path from Jquery but had trouble with 2 data types being passed in the post.

This is from the aspx.cs file, I am trying to get the value of the listDrop.SelectedItem.Text

protected void ListDrop_SelectedIndexChanged(object sender, EventArgs e)
    {
        string fullFileName = Path.Combine("~/Uploads/", listDrop.SelectedItem.Text);
        string[] filePaths = Directory.GetFiles(Server.MapPath(fullFileName));
        List<ListItem> files = new List<ListItem>();
        foreach (string filePath in filePaths)
        {
            files.Add(new ListItem(Path.GetFileName(filePath), filePath));
        }
        GridView1.DataSource = files;
        GridView1.DataBind();
    }

Solution

  • The easier way to do that is enabling Session in your HttpHandler and getting the last selected path from there.

    In code behind of your webform save the path in Session

    protected void ListDrop_SelectedIndexChanged(object sender, EventArgs e)
    {
        string fullFileName = Path.Combine("~/Uploads/", listDrop.SelectedItem.Text);
        Session["fullFileName"] = fullFileName;
    }
    

    In your HttpHander add IRequiresSessionState and retrieve the path from Session.

    public class WebHandler : IHttpHandler, IRequiresSessionState
    {
    
        public void ProcessRequest(HttpContext context)
        {
            var fullFileName = context.Session["fullFileName"];
        }
    }
    

    Selected value will be available for a client until Session expires. By default that is 20 minutes without getting any new request. However this time can be increased by changing configuration. Additionally you can detect Session has expired in your code because context.Session["fullFileName"] would return null.