Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the name 'Request' does not exist when writing in a class.cs file?

Tags:

c#

asp.net

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?

like image 518
Different111222 Avatar asked May 03 '12 21:05

Different111222


2 Answers

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.

like image 122
Tim Schmelter Avatar answered Nov 07 '22 05:11

Tim Schmelter


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.

like image 1
jaressloo Avatar answered Nov 07 '22 03:11

jaressloo