为什么在写入class.cs文件时不存在名称"Request"? [英] Why the name 'Request' does not exist when writing in a class.cs file?

查看:82
本文介绍了为什么在写入class.cs文件时不存在名称"Request"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将以下代码从c#aspx.cs文件移动到独立的class.cs文件中.

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"];

用于驻留在aspx.cs文件的page_load中的这段代码工作正常,但是会在类文件中引发错误.

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文件中,请求"不需要使用",并且在这种情况下不提供任何使用.

The 'Request' needs no 'using' when in a aspx.cs file, and offers none in this context.

我该如何解决这个问题?

How do I solve this problem?

推荐答案

Request 是页面类的属性.因此,您不能从独立"类访问它.

Request is a property of the page class. Therefore you cannot access it from a "standalone" class.

但是,无论如何,您都可以通过 HttpContext.Current获取HttpRequest.

However, you can get the HttpRequest anyway via HttpContext.Current

 var request = HttpContext.Current.Request;

请注意,即使在静态方法中也可以使用.但是仅当您使用HttpContext(因此不在Winforms应用程序中)时.因此,您应该确保它不是 null :

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.

这篇关于为什么在写入class.cs文件时不存在名称"Request"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆