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.Current
var request = HttpContext.Current.Request;
Note 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
:
if (HttpContext.Current != null)
{
var request = HttpContext.Current.Request;
}
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.
The reason it doesn't work is because you cannot access server variables in a class library project.
You should avoid attempting to make this act like a web class and instead pass the information you need to the class object via a normal parameter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With