ASP.NET 网站 禁止未登录用户查看及下载指定目录下的文件

通过IHttpHandler 保护 upload 的文件只能被登录用户下载和查看

using System.Web;
/// 
/// FileProtectHandler 防止未登陆用户下载文件
/// 
public class FileProtectHandler : IHttpHandler
{
    public bool IsReusable
    {
        get
        {
            return true;
        }
    }
    public void ProcessRequest(HttpContext context)
    {
        if (context.User != null && context.User.Identity.IsAuthenticated)//已经登录则下载文件
        {
            DownloadFile(context);
        }
        else
        {
            context.Response.Redirect("~/Login.aspx");//未登录则转到登录页面
         //   context.Response.Write("False");
        }
    }
    protected void DownloadFile(HttpContext context)
    {
        context.Response.Buffer = true;
        context.Response.Clear();
        context.Response.AddHeader("content-disposition", context.Request.Url.AbsolutePath);
        context.Response.ContentType = "text/plain";
        context.Response.WriteFile(context.Server.MapPath(context.Request.Url.AbsolutePath));
    }
}
   
    
      
    
  



你可能感兴趣的:(ASP.NET 网站 禁止未登录用户查看及下载指定目录下的文件)