I would like to move the following piece of code from a c# aspx.cs file into a stand alone class.cs file.
string getIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (String.IsNullOrEmpty(getIP)) getIP = Request.ServerVariables["REMOTE_ADDR"];
This piece of code used to reside in the page_load of an aspx.cs file worked just fine, but it raises an error in the class file.
The ‘Request’ needs no ‘using’ when in a aspx.cs file, and offers none in this context.
How do I solve this problem?
Request is a property of the page class. Therefore you cannot access it from a “standalone” class.
However, you can get the HttpRequest anyway via
HttpContext.CurrentNote that this works even in a static method. But only if you’re in a HttpContext(hence not in a Winforms application). So you should ensure that it’s not
null:Edit: Of course you can also pass the request as parameter to the method that consumes it. This is good practise since it doesn’t work without. On this way every client would know immediately whether this class/method works or not.