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