ASP .NET MVC - 文件访问

本文关键字:文件 访问 MVC NET ASP | 更新日期: 2023-09-27 18:33:42

我正在尝试以这样的方式在我的应用程序中配置路由:文件的路径应该适用于除一个特殊目录之外的每个目录。并且对本目录中的文件的访问应由我的控制器操作处理。如果我这样写:

routes.Map("Specialfolder/{name}", "Controller", "Action");

它仅适用于不存在的文件。控制器未捕获现有文件的路由

如果我添加这一行:

routes.RouteExistingFiles = true;

处理我的文件夹中的文件是可以的。但是不再路由其他目录中的文件。如何解决这个问题?

ASP .NET MVC - 文件访问

下面是

可以使用的示例 ActionFilter 示例代码片段

public class UriActionFilter : System.Web.Mvc.ActionFilterAttribute
{
    public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
    {
        if (System.Threading.Thread.CurrentPrincipal.Identity.IsAuthenticated)
        {
            // Sample: somehow identify the user, in case of a custom identity, replace the below line to get the user identifier
            var user = System.Threading.Thread.CurrentPrincipal.Identity.Name;
            // get the parameter that will let you know what is the image or path that is being requested now
            var ctxParams = filterContext.ActionParameters;
            // if the user does not have the permission to view, return 403
            filterContext.RequestContext.HttpContext.Response.StatusCode = 403;
            return;
        }
        base.OnActionExecuting(filterContext);
    }
}

在此代码段中,您必须替换为相应的服务调用等。

W.R.TO OnAuthorization,我提到您可以使用,以便任何可以访问图像的人都可以直接命中URI,并且可以过滤使用。我们使用这种方式直接限制给定用户的 URI 访问。

这将帮助您覆盖控制器获得的每个请求的 MVC 授权。这更像是 URI 本身的限制。但是,上述操作过滤器也可以满足您的情况,因为解析 uri 参数有时可能非常棘手。