Check for authentication in VirtualFileMapping

I have an inherited FileSystemMapping that checks if the user is authenticated before returning the file.

public class AuthenticatedFileSystemMapping : FileSystemMapping
        public AuthenticatedFileSystemMapping(string alias, string rootDirectoryPath) : base(alias, rootDirectoryPath) 
        { }

        public override IVirtualFile GetFile(string virtualPath)
            var req = HostContext.GetCurrentRequest();
            if (!req.IsAuthenticated())
                return null;  

            return base.GetFile(virtualPath);

This no longer works in CORE because HostContext.GetCurrentRequest() fails. I found and implemented the solution shown in the thread below, and it works well, but I have also read that you don’t really recommend doing this and there is a performance hit associated with it.

Therefore, I am wondering if there might be an alternate way to check if the current user is authenticated inside a FileSystemMapping without using HostContext.GetCurrentRequest().


You can’t access the current HTTP request via a singleton unless you register .NET Core’s HttpContextAccessor which is what makes it available in a singleton context if it’s called within the HTTP Worker Thread. The overhead is the cost for doing this which is why it’s disabled by default in .NET Core whereas in classic ASP .NET they preferred convenience over performance which is why it was always enabled.

I personally dislike hidden code accessing the Request Context via a singleton like this which is why I recommended doing the authentication check in a PreRequestFilter in my previous answer: Throw 401, want to see browser 401 page, not ASP.NET uncaught exception page

But if you want to access the Request Context from a VFS provider (or any method which doesn’t have access to the request context) you’ll need to access it via the singleton, just be aware that it will only work when called from a HTTP Worker Request Thread, i.e. not from a Background Thread.