仅向授权用户提供 ASP.NET 静态文件



我正在尝试保护我的项目下只有一个静态文件的文件夹,.htm.js文件的组合。我尝试创建自定义HttpHandler,例如:

public class StaticFilesHttpHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        if (context.Request.IsAuthenticated)
        {
            // continue with the request
        }
        else
        {
            throw new HttpResponseException(HttpStatusCode.Unauthorized);
        }
    }
    public bool IsReusable => false;
}

然后注册它以通过Route.Config与路由一起使用

routes.RouteExistingFiles = true;
routes.Add("helpRoute", new Route("folder/*.htm", new StaticFilesRouteHandler ()));

以及用于提供

public class StaticFilesRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext context)
    {
        return new StaticFilesHttpHandler ();
    }
}

以及通过web.config system.webServer

<handlers>
  <add name="StaticFileHandler" verb="GET" path="~/help/default.htm" type="StaticFilesHttpHandler "/>
</handlers>

文件夹中的文件由第三方提供。我要在文件夹中的js文件中调用一个函数,然后将用户重定向到其子结构中的正确.htm文件。我不希望用户能够键入 url 并访问任何文件。我做错了什么?

您可以将类型更改为TransferRequestHandler并确保路径正确。

<handlers>
  <add name="StaticFileHandler" verb="GET" path="~/help/default.htm" type="TransferRequestHandler" />
</handlers>

在 global.asax 文件中,可以访问 Application_BeginRequest 中的请求,以验证请求是否已通过身份验证。

最新更新