无法使用webforms的HttpHandler下载文件

时间:2018-03-22 13:36:21

标签: c# webforms httphandler

我使用HttpHandler从webforms aspx页面下载文件。如果文件名没有逗号,一切都OK。如果有 - 我收到错误(无法在服务器上找到文件)。 这是用于下载文件的HttpHandler代码:

public class DocDownloadHandler : IHttpHandler
{
    public bool IsReusable
    {
        get { return true; }
    }

    public void ProcessRequest(HttpContext context)
    {
        int npId = int.Parse(context.Request["npId"]);
        string fileName = context.Request["fileName"];
        fileName = HttpUtility.UrlDecode(fileName);
        string filePath = ConfigurationManager.AppSettings["DocsDir"].Trim('\\') + "\\" + npId + "\\" + fileName;

        WebClient webClient = new WebClient();
        using (Stream stream = webClient.OpenRead(filePath))
        {
            byte[] data1 = new byte[stream.Length];
            stream.Read(data1, 0, data1.Length);

            context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));
            context.Response.BinaryWrite(data1);

            context.Response.Flush();
            context.Response.SuppressContent = true;
            context.ApplicationInstance.CompleteRequest();
        }
    }
}

我该怎样做才能下载带有逗号的文件,可能是其他招致相同问题的标志?

1 个答案:

答案 0 :(得分:0)

在将资源路径提交到WebClient之前尝试对资源路径进行URL编码:

string fileURI = System.Web.HttpUtility.UrlEncode(filePath);
WebClient webClient = new WebClient();
using (Stream stream = webClient.OpenRead(fileURI))
{
    ...
}