从Webhandler.ashx文件中的.aspx.cs获取变量值

时间:2018-02-11 18:29:26

标签: c# asp.net webforms generic-handler

我正在尝试接受通过httphandler上传的文件,我需要从.aspx的下拉列表中找到的路径。我在aspx.cs文件中将路径作为变量,但我无法在.ashx文件中访问它。我认为它与web.config文件有关我将.ashx的引用添加到system.web配置但没有更改。

'<%@ 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;
    }
 }

}

我试图从Jquery传递路径但是在帖子中传递了2种数据类型时遇到了麻烦。

这是来自aspx.cs文件,我试图获取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();
    }

1 个答案:

答案 0 :(得分:0)

更简单的方法是在HttpHandler中启用Session并从那里获取最后选择的路径。

在您的网络表单后面的代码中保存Session

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

在你的HttpHander中添加 IRequiresSessionState 并从Session中检索路径。

public class WebHandler : IHttpHandler, IRequiresSessionState
{

    public void ProcessRequest(HttpContext context)
    {
        var fullFileName = context.Session["fullFileName"];
    }
}

在会话到期之前,客户端可以使用所选值。默认情况下,这是20分钟没有得到任何新请求。但是这个时间可以增加changing configuration。此外,您可以在代码中检测到Session已过期,因为context.Session["fullFileName"]将返回null。