webform
新建WebForm

新建Global.asax
using System;
using System.Web.Routing;
namespace FileAuthStu01
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.RouteExistingFiles = true;
//如果没有处理则默认还是会走静态文件返回,IgnoreRoute是MVC才有的
//RouteTable.Routes.IgnoreRoute("Content/{*relpath}");
RouteTable.Routes.MapPageRoute(
"ImageRoute",
"image/imgs/{imageName}",
"~/ImageHandler.aspx",
true,
new RouteValueDictionary {
{
"imageName", "" } });
}
}
}
修改web.config
<system.webServer>
<!-- 确保所有请求都经过ASP.NET的管道处理 -->
<modules runAllManagedModulesForAllRequests="true" />
<handlers>
</handlers>
<!--设置默认起始页面-->
<defaultDocument>
<files>
<clear />
<add value="index.aspx" />
</files>
</defaultDocument>
</system.webServer>
新建ImageHandler.aspx
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Web;
namespace FileAuthStu01
{
public partial class ImageHandler : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//TODO 验证是否有权限,按照逻辑自己实现
//方法1 获取jwt等授权信息判断是否有权限查看,适合点击下载事件一般用于POST请求
//var authData = Request.Headers.Get("Authorization");
//方法2 将缓存的参数通过query参数写入,实现显示一次就将缓存取消阅后即焚的效果
//也可以增加一些参数,比如设置图片大小等参数,一般用于GET请求
string imageName = RouteData.Values["imageName"] as string;
if (string.IsNullOrEmpty(imageName))
{
//文件不存在
Response.StatusCode = 404;
return;
}
var imagePath = Server.MapPath($"~/image/imgs/{
imageName}");
if (!File.Exists(imagePath))
{
//文件不存在
Response.StatusCode = 404;
return;
}
var fileStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

最低0.47元/天 解锁文章
877

被折叠的 条评论
为什么被折叠?



