.net core 3.0 MVC learning - the static file permissions management middleware

// app.UseWhen (
             //     C => c.Request.Path.Value.Contains ( "Upload"),
             //     _ => _.UseMiddleware <AuthorizeStaticFilesMiddleware> ()); // for access control 
            app.Map ( " / the Upload " ,
                C => c.UseMiddleware <AuthorizeStaticFilesMiddleware> ()); // for access control
///  <the Summary> 
    /// file management middleware
     ///  </ the Summary> 
    public  class AuthorizeStaticFilesMiddleware
    {
        private readonly RequestDelegate _next;

        public AuthorizeStaticFilesMiddleware(
            RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context, IAuthorizationService authorService)
        {
            var url = context.Request.Path;
            var sid = context.Request.Headers["sid"].ToString();
            if (string.IsNullOrEmpty(sid))
            {
                throw new Exception("resource 403 forbidden sid is empty");
            }

            var result = ValidateResourceAuthor(url,sid);

            if (result == false)
            {
                await context.ForbidAsync();
            }

            await _next(context);
        }
        public bool ValidateResourceAuthor(string url,string sid)
        {
            // was loginUser = UserHelper._GetUser (req.SID);

            if (string.IsNullOrEmpty(url))
            {
                throw new Exception("url is empty");
            }
            //https://localhost:5001/assets/upload/images/20181018/0d9819d2-14d2-47eb-a763-be9d19c69e42.jpg
            url = url.Trim().ToLower();

            if (url.EndsWith(".mp4") || url.EndsWith(".mp3"))
            {
                //...
            }

            return true;
        }

Middleware:

 

 

  .NET Core middleware class using the convention, agreed on between the middleware class method must include a call Invoke's,

       Map expansion as a convention to create a pipeline branch. Map based on the given path matches the request to create a branch pipeline request. If a given request path beginning of the path, the branch is executed

Guess you like

Origin www.cnblogs.com/zhaocha/p/12195245.html
Recommended