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

后端 未结 2 1234
北恋
北恋 2021-02-12 12:48

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_FORWARD         


        
相关标签:
2条回答
  • 2021-02-12 13:09

    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.

    0 讨论(0)
  • 2021-02-12 13:34

    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.

    0 讨论(0)
提交回复
热议问题