Ciao a tutti in questo articolo ho deciso di inserire un metodo per scrivere in Request.ServerVariables...
Come tutti sapete questa collection è ReadOnly... per fortuna che c'è Reflection!!!!
In primis creiamo un HttpModule, questo ci permetterà di "trappare" la richiesta e di scriverci dentro... ovviamente non è indispensabile, ma così il metodo può essere riusato in tutte le richieste.
In secundis, utilizziamo un pò di reflection per rendere scrivibile la collection...
In definitiva, possiamo fare così:
using System;
using System.Text;
using System.Web;
using System.Reflection;
using System.Collections.Specialized;
public class ServerVariableWriter : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(Context_BeginRequest);
}
protected void Context_BeginRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
BindingFlags temp = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
MethodInfo addStatic = null;
MethodInfo makeReadOnly = null;
MethodInfo makeReadWrite = null;
Type type = application.Request.ServerVariables.GetType();
MethodInfo[] methods = type.GetMethods(temp);
foreach (MethodInfo method in methods)
{
switch (method.Name)
{
case "MakeReadWrite": makeReadWrite = method;
break;
case "MakeReadOnly": makeReadOnly = method;
break;
case "AddStatic": addStatic = method;
break;
}
}
makeReadWrite.Invoke(application.Request.ServerVariables, null);
string[] values = { "KEY", "VALUE" };
addStatic.Invoke(application.Request.ServerVariables, values);
makeReadOnly.Invoke(application.Request.ServerVariables, null);
}
}
dove
KEY e
VALUE sono rispettivamente la chiave della variabile server ed il suo valore. Per recuperare il valore, una volta registrato il modulo nel web.config, basta fare semplicemente:
string value = Request.ServerVariables["KEY"];