Can web forms and generic handlers (ashx files) share a common ancestor class (or base page)?
If one has an ASP.net web site whose web forms all inherit from a common base page--which checks things like authentication and redirects when a session has expired, etc--is there a way to use this base class in a ashx handler? I started going down that r开发者_Go百科oad by inheriting the base page class in the handler and realized this might not be a recommended practice. Any thoughts on how to avoid code duplication here?
Can this
public class FooHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
become this
public class FooHandler : BasePageClass, IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
I get the following warning, which is what made me reconsider what I was doing:
FooHandler.ProcessRequest(System.Web.HttpContext) hides inherited member System.Web.UI.Page.ProcessRequest(System.Web.HttpContext). To override that implementation, add the override keyword. Otherwise add the new keyword.
If you set the parent class ProcessRequest as virtual you can override it in the child class and call the base class method from inside the overridden method.
public abstract class ParentHandler : IHttpHandler, IRequiresSessionState
{
protected WebConnectHandler Context;
public virtual void ProcessRequest(HttpContext context)
{
Context = new WebConnectHandler(context);
}
//...
}
//...
public class ChildHandler : ParentHandler
{
public override void ProcessRequest(HttpContext context)
{
base.ProcessRequest(context);
//the rest of your code
}
}
//...
You are now discovering why the OO guru types always vote for composition over inheritance. Anyhow, doing exactly what you want to do is pretty tricky as, while a System.Web.UI.Page implements IHttpHandler (if I recall correctly) there is lots of internal processing you can't defeat to get back to your own handler.
The easiest fix would be to try and move as many of those functions off the monster base page class into their own classes--or better yet IHttpModules where it makes sense to handle stuff like session expiration--in order to decouple things.
精彩评论