asp.netWebForm未授权访问服务器资源问题
问题描述
在未授权的情况,可以随意在地址栏访问到服务器的pdf
解决方案:
1、webconfig
name=“PdfHandler”:指定处理程序的唯一名称。
path=“.pdf":定义此处理程序将处理的请求路径,这里是任何以 .pdf 结尾的请求。
verb="”:指定此处理程序将响应的 HTTP 方法类型,星号 * 表示接受所有类型的方法(如 GET、POST 等)。
type=“DTcms.Web.Security.PdfHandler, DTcms.Web”:指定处理程序的完全限定类型名和所在的程序集,这里 PdfHandler 类位于 DTcms.Web 程序集的 DTcms.Web.Security 命名空间下。
resourceType=“Unspecified”:指定处理程序所处理的资源类型。Unspecified 表示没有具体指明资源类型,可以是任意类型的资源。
<system.webServer>
<handlers>
<add name="PdfHandler" path="*.pdf" verb="*" type="DTcms.Web.Security.PdfHandler, DTcms.Web" resourceType="Unspecified" />
</handlers>
</system.webServer>
2、新建一个一般处理程统一处理pdf资源的请求
public class PdfHandler : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
// 获取请求的路径
string filePath = context.Request.Path;
// 提取动态部分:日期和文件ID
string[] pathParts = filePath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
if (pathParts.Length < 3)
{
context.Response.StatusCode = 400; // Bad Request
context.Response.End();
return;
}
string yearMonth = pathParts[1]; // 例如:202407
string fileId = pathParts[2].Replace(".pdf", ""); // 例如:54302406172689
// 构造实际文件路径
string physicalFilePath = GetFilePath(yearMonth, fileId);
// 检查用户是否授权
if (!UserIsAuthorized(context))
{
context.Response.StatusCode = 403; // Forbidden
context.Response.End();
return;
}
// 确保文件存在
if (!File.Exists(physicalFilePath))
{
context.Response.StatusCode = 404; // Not Found
context.Response.End();
return;
}
// 设置响应类型
context.Response.ContentType = "application/pdf";
context.Response.AddHeader("Content-Disposition", "inline; filename=" + Path.GetFileName(physicalFilePath));
context.Response.WriteFile(physicalFilePath);
context.Response.End();
}
private string GetFilePath(string yearMonth, string fileId)
{
// 根据日期和文件ID构造实际文件路径
return HttpContext.Current.Server.MapPath("~/tjbg/" + yearMonth + "/" + fileId + ".pdf");
}
private bool UserIsAuthorized(HttpContext context)
{
// 实现你的授权检查逻辑
return IsAdminLogin(context);
}
public bool IsReusable
{
get { return false; }
}
}