C# 为什么在 class.cs 文件中写入时名称“请求”不存在?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10439709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why the name 'Request' does not exist when writing in a class.cs file?
提问by Different111222
I would like to move the following piece of code from a c# aspx.cs file into a stand alone class.cs file.
我想将以下代码从 ac# aspx.cs 文件移动到独立的 class.cs 文件中。
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.
这段代码以前驻留在 aspx.cs 文件的 page_load 中工作得很好,但它在类文件中引发了错误。
The 'Request' needs no 'using' when in a aspx.cs file, and offers none in this context.
“请求”在 aspx.cs 文件中不需要“使用”,并且在此上下文中不提供任何内容。
How do I solve this problem?
我该如何解决这个问题?
采纳答案by Tim Schmelter
Requestis 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
但是,您无论如何都可以通过以下方式获取 HttpRequest 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:
请注意,这即使在静态方法中也有效。但前提是您在 HttpContext 中(因此不在 Winforms 应用程序中)。所以你应该确保它不是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.
编辑:当然,您也可以将请求作为参数传递给使用它的方法。这是一个很好的做法,因为没有它就行不通。通过这种方式,每个客户都会立即知道这个类/方法是否有效。
回答by jaressloo
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.
您应该避免尝试使其像 Web 类一样运行,而是通过普通参数将您需要的信息传递给类对象。

