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

来源:互联网 发布:重庆专业网络广告公司 编辑:程序博客网 时间:2024/05/01 14:13

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

using System.Web;/// <summary>/// FileProtectHandler 防止未登陆用户下载文件/// </summary>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));    }}
   <system.webServer>    <handlers>      <add name="FileProtect" path="upload" verb="*" type="FileProtectHandler,App_Code"  />    </handlers>  </system.webServer>



0 0
原创粉丝点击