HttpHandler fire only if file doesn't exist

后端 未结 3 866
长情又很酷
长情又很酷 2021-02-09 09:11

I\'m trying to create a HTTP handler to handle all requests to a folder but I only want it to fire if the files requested don\'t exist (EG: Request comes in for file X, if X exi

3条回答
  •  北海茫月
    2021-02-09 09:53

    Probably you would want to implement an HttpModule. Otherwise you are fighting with all the other HttpHandlers that are vying for the request.

    This should get you started....

    You can decide where in the request lifecycle you want to perform your check and react. See this article for some background

    using System;
    using System.IO;
    using System.Web;
    
    namespace RequestFilterModuleTest
    {
        public class RequestFilterModule : IHttpModule
        {
            #region Implementation of IHttpModule
    
            /// 
            /// Initializes a module and prepares it to handle requests.
            /// 
            /// 
            /// An  that provides access to the methods, 
            /// properties, and events common to all application objects within an ASP.NET application 
            /// 
            public void Init(HttpApplication context)
            {
                context.BeginRequest += ContextBeginRequest;
            }
    
            /// 
            /// Disposes of the resources (other than memory) used by the module that implements .
            /// 
            public void Dispose()
            {
            }
    
            private static void ContextBeginRequest(object sender, EventArgs e)
            {
                var context = (HttpApplication) sender;
    
                // this is the file in question
                string requestPhysicalPath = context.Request.PhysicalPath;
    
                if (File.Exists(requestPhysicalPath))
                {
                    return;
                }
    
                // file does not exist. do something interesting here.....
            }
    
            #endregion
        }
    }
    

    
    
        ...............................
        
        ...........................
            
                
                
            
        
        ...................
    
    

提交回复
热议问题