Action Filters allows you to connect to specific MVC events only when HTTP modules allow you to connect to ASP.Net events, so even in MVC you will need to implement the appropriate interface to implement the HTTP module and HTTP handler. In addition, if you want your functions to be executed only once per Http request, you should use the HttpModule. ActionFilters can run multiple times in a single trip to the server. To explain the HTTP modules and HTTP handlers, the HTTP module and HTTP handler are used by MVC to enter preprocessing logic in the request chain.
HTTP handlers are an extension-based preprocessor, while an HTTP module is an event-based preprocessor. For example, if you want to change the way jpg
files are processed, you will use your own HTTP handler, and if you want to perform additional logic during request processing, you will implement a custom HTTP module. There is always only one HTTP handler for a particular request, but there can be several HTTP modules.
To implement the HTTP handler, you implement the IHTTPHandler
class and implement the ProcessRequest
methods and the IsResuable
property. The IsResuable
property determines whether a handler can be reused or not.
public class MyJpgHandler: IHttpHandler { public bool IsReusable { get { return false; } } public void ProcessRequest(HttpContext context) { } }
Next, we need to specify what kind of request will be processed by our custom handler in the web.config
:
<httpHandlers> <add verb="*" path="*.jpg" type="MyJpgHandler"/> </httpHandlers>
To implement the HTTP module, we need to implement the IHttpModule
and register the necessary events in the init
method. As a simple example, if we want to register all requests:
public class MyHttpModule: IHttpModule { public MyHttpModule() {} public void Init(HttpApplication application) { application.BeginRequest += new EventHandler(this.context_BeginRequest); application.EndRequest += new EventHandler(this.context_EndRequest); } public void context_BeginRequest(object sender, EventArgs e) { StreamWriter sw = new StreamWriter(@ "C:\log.txt", true); sw.WriteLine("request began at " + DateTime.Now.ToString()); sw.Close(); } public void context_EndRequest(object sender, EventArgs e) { StreamWriter sw = new StreamWriter(@ "C:\log.txt", true); sw.WriteLine("Request Ended at " + DateTime.Now.ToString()); sw.Close(); } public void Dispose() {} }
And register our module:
<httpModules> <add name="MyHttpModule " type="MyHttpModule " /> </httpModules>