【问题标题】:HttpContext at Handler处理程序处的 HttpContext
【发布时间】:2010-08-30 08:19:54
【问题描述】:

为了保护下载文件,我创建了 http 处理程序,如下所示:

  public void ProcessRequest(HttpContext context)
  {
        string user = HttpContext.Current.User.Identity.Name;
        FilePermissionHelper helper = new FilePermissionHelper(user);
        string path = context.Request.Form["file"];
        bool canDownload = helper.HasPermission(FileOperation.Download, path);
        if (!canDownload)
        {
            context.Response.StatusCode = 403;
            context.Response.End();
            return;
        }
        else
        {
            string fileName=String.Format(@"{0}App_Data\files{1}",HostingEnvironment.ApplicationPhysicalPath,path.Substring(1));
            context.Response.ContentType = "application/octet-stream";
            context.Response.AppendHeader("Content-Disposition", fileName);
            context.Response.TransmitFile(fileName);
            context.Response.End();
        }
 }

它使用 HttpContext.Current.User。

当我使用这个处理程序来服务文件时:

  protected void tvFile_NodeClick(object sender, RadTreeNodeEventArgs e)
  {
        string url = new Uri(String.Format("{0}/{1}", Request.Url.GetLeftPart(UriPartial.Authority),HandlerName)).AbsoluteUri;
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        string data = String.Format("file={0}", e.Node.Value);
        byte[] buffer = Encoding.UTF8.GetBytes(data);
        req.Method = "POST";
        req.ContentType = "application/x-www-form-urlencoded";
        req.ContentLength = buffer.Length; 
        Stream reqst = req.GetRequestStream(); 
        reqst.Write(buffer, 0, buffer.Length);
        reqst.Flush();
        reqst.Close();
        byte[] bytes=ReadFully(((HttpWebResponse)req.GetResponse()).GetResponseStream());
        HttpContext.Current.Response.ContentType = "application/octet-stream";
        HttpContext.Current.Response.AppendHeader("Content-Disposition", String.Format("attachment; filename={0}",e.Node.Text));
        HttpContext.Current.Response.BinaryWrite(bytes);
        HttpContext.Current.Response.End();

 }

我在处理程序中得到了 HttpContext.Current.User=null。当然我可以使用 POST data,Session,但我想通过 HttpContext 解决这个问题。顺便说一句,当我在客户端(通过 js)进行 POST 时一切正常:HttpContext.Current.User 传递给处理程序。怎么了?谢谢。

【问题讨论】:

    标签: asp.net httphandler httpcontext


    【解决方案1】:

    使用IHttpHandler 将另一个名为IRequiresSessionState 的接口添加到您的处理程序中,您可能会正确获取用户对象

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-21
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 2019-09-16
      • 1970-01-01
      相关资源
      最近更新 更多