Httpcontext. Current is null during unit testing.
Some DLL files are bound to httpcontext (the major reason is that most of ...net files are used for web projects)
Or try to use these DLL in Windows form or console...
Of course, httpcontext. current can be assigned a value... the simplest way is to directly add an httpcontext to it.
httprequest request = New httprequest ( " " , " http: // localhost " , " " );
httpcontext. current = New httpcontext (request, New httpresponse ( New system. io. stringwriter ();
Well, if you need a session, add the followingCode
System. Web. sessionstate. sessionstateutility. addhttpsessionstatetocontext (
Httpcontext. Current, New Httpsessionstatecontainer
( "" ,
New Sessionstateitemcollection (),
New Httpstaticobjectscollection (),
20000 ,
True ,
Httpcookiemode. usecookies,
Sessionstatemode. Off,
False
)
);
The problem arises again... some code will read httpheader... for example, what Ip is often stored here
Even more depressing is that the class of httpcontext is often unable to set httpheader .....
Because this is read-only .......
In fact, read-only is basically a lie in. net, so it is a bit useful during compilation.
When running, do not read-only connections to private can be obtained through reflection.
Use reflection to assign values to httpheader.
VaR instance = Httpcontext. Current. Request. servervariables;
Type type = Instance. GetType ();
Bindingflags temp = Bindingflags. nonpublic | Bindingflags. Instance | Bindingflags. Static;
Methodinfo addstatic = Null ;
Methodinfo makereadonly = Null ;
Methodinfo makereadwrite = Null ;
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 (instance, Null );
List < String [] > List = New List < String [] > ();
String IP = Servicecontext. IPaddress;
List. Add ( New String [] { " Http_x_forwarded_for " , IP });
List. Add ( New String [] { " Http_client_ip " , IP });
List. Add ( New String [] { " Http_x_forwarded " , IP });
List. Add ( New String [] { " Http_x_cluster_client_ip " , IP });
List. Add ( New String [] { " Http_forwarded_for " , IP });
List. Add ( New String [] { " Http_forwarded " , IP });
List. Add ( New String [] { " Remote_addr " , IP });
Foreach ( String [] Values In List)
Addstatic. Invoke (instance, values );
Makereadonly. Invoke (instance, Null );