开发者

HttpContext at Handler

开发者 https://www.devze.com 2023-01-13 09:48 出处:网络
For protect download files purposing I created http handler liket this: public void ProcessRequest(HttpContext context)

For protect download files purposing I created http handler liket this:

  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();
        }
 }

It uses HttpContext.Current.User.

When I use this handler for serve files like:

  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.R开发者_Go百科esponse.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();

 }

I got HttpContext.Current.User=null at handler. Sure I can use POST data,Session, but I want resolve this issue through HttpContext. BTW when I make POST at client(by js) all is ok: HttpContext.Current.User passed to handler. What's wrong? Thanks.


Add another interface called IRequiresSessionState to your handler with IHttpHandler and you will probably get the user oject correctly

0

精彩评论

暂无评论...
验证码 换一张
取 消