Set custom Server Variable with HTTPModule

Set custom Server Variable with HTTPModule

Impostare le Variabili Server con un modulo HTTP

Oggi vediamo come impostare le ServerVariables in C# dato che di default non è esposta la Proprietà Set.

Per poter effettuare la Set di una Server Variables custom è necessario definire un HTTPModule.

Lo snippet per il Modulo HTTP è il seguente:

using System; using System.Web; using System.Reflection; namespace MyModules { public class MyModule : IHttpModule { public MyModule(){} public void Dispose(){} public void Init(HttpApplication context) { context.BeginRequest += new EventHandler(context_BeginRequest); } void context_BeginRequest(object sender, EventArgs e) { HttpApplication application = (HttpApplication)sender; this.SetSV("HTTP_MyVar1", "My Server Variables 1", application); this.SetSV("HTTP_MyVar2", "My Server Variables 2", application); } //Set Server Variable void SetSV(string nome, string valore, HttpApplication application) { BindingFlags temp = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; MethodInfo addS = null; MethodInfo mRO = null; MethodInfo mRW = null; Type type = application.Request.ServerVariables.GetType(); MethodInfo[] methods = type.GetMethods(temp); foreach (MethodInfo method in methods) { switch (method.Name) { case "MakeReadWrite": mRW = method; break; case "MakeReadOnly": mRO = method; break; case "AddStatic": addS = method; break; } } mRW.Invoke(application.Request.ServerVariables, null); string[] values = { nome, valore }; addS.Invoke(application.Request.ServerVariables, values); mRO.Invoke(application.Request.ServerVariables, null); } } }

Ricordatevi di aggiungere l’HTTPModule nel Web.config come segue:

<httpModules> <add name="MyModule" type="MyModules.MyModule"/> </httpModules>

Scarica lo snippet completo: Set_Server_Variables.zip (2,85 kb)

Enjoy Snippet!

3 commenti

comments user
Mario

Hi Nicola,

In what version of IIS have you tested this?

I need to set a session variable in an httpmodule in IIS 7.0, and I’ve tried this, but no sucess :S

    comments user
    Nicola Celiento

    Under IIS 7.0 you need to add the <httpModules> entry

    (<add name=”MyModule” type=”MyModules.MyModule”/>

    under <system.webServer> too.

    I hope it hepls you!

    Enjoy!

      comments user
      Mario

      Thanks for the quick reply

      Yes, the module is being executed.

      The problem is the Set of the ServerVariable.

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *