Interagir avec les pages ASP.NET avant l'Init.
Publié par Fabrice Michellonet sous le(s) label(s) ASP.NET , Claymore le 21 avril 2010Au cours du développement de Claymore, pour la partie ASP.NET plus précisément, j'ai eu besoin de trouver un hook me donnant la possibilité d'interagir avec les pages avant les events que l'on trouve sur l'objet Page.
J'ai tout d'abord pensé tripatouiller dans le fichier Global.asax... sans finalement avoir trouvé ce que je souhaitais. Par contre, en fouillant un peu du côté des HttpModule je suis arrivé à la solution suivante :
using System;
using System.Reflection;
using System.Web;
using System.Web.UI;
namespace Claymore.Web
{
/// <summary>
///
/// </summary>
public class ClaymoreHttpModule : IHttpModule
{
#region Fields
private HttpApplication _application;
#endregion
/// <summary>
/// Initializes a module and prepares it to handle requests.
/// </summary>
/// <param name="context"> </param>An <see cref="T:System.Web.HttpApplication"/> that provides access to the methods, properties, and events common to all application objects within an ASP.NET application
public void Init(HttpApplication context)
{
if(context == null)
throw new ArgumentNullException("context");
_application = context;
context.PostMapRequestHandler += onPostMapRequestHandler;
}
/// <summary>
/// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"/>.
/// </summary>
public void Dispose(){}
/// <summary>
/// Handle PostMapRequest event.
/// </summary>
/// <param name="sender"> </param>The sender.
/// <param name="e"> </param>The <see cref="System.EventArgs"/> instance containing the event data.
private void onPostMapRequestHandler(object sender, EventArgs e)
{
Page pageHandler;
if ((pageHandler = _application.Context.Handler as Page) != null)
pageHandler.PreInit += HandlePreInit;
}
/// <summary>
/// Handles the pre init event.
/// </summary>
/// <param name="sender"> </param>The sender.
/// <param name="e"> </param>The <see cref="System.EventArgs"/> instance containing the event data.
protected virtual void HandlePreInit(object sender, EventArgs e)
{
Page page = sender as Page;
if (page != null){
// Et voila, on a un pointeur sur une page, et l'on peut interagir avec elle avant l'événement Init.
// Ajouter du code ici.
}
}
}
}
L'un d'entre vous connaîtrait-il une solution équivalente à base de HttpHandler ou autre?