您的位置:首页 > 其它

解决办法:The name 'Response' does not exist in the current context

2017-09-07 19:22 1246 查看
问题描述:ASP.net,在使用ClosedXML抽取excel保存时,出错:The
name 'Response' does not exist in the current context. / 当前上下文中不存在名称'Response'。


原因分析:Response 对象可以在页面的任何地方使用,如在 Page 对象事件中使用,在按钮单击事件中使用或在函数中使用,但不能在非页面类中使用。即
Response 对象所在的类必须继承 System.Web.UI.Page 类(ASP.NET(C#)实践教程(第 2 版)- 第三章)。其他即使使用using System.Web.UI 也无法使用Page.Response属性。否则编译时报错:当前上下文中不存在名称"Response"

解决办法:使用System.Web.HttpContext.Current.Response来代替,既都可获取当前
HTTP 响应的 HttpResponse 对象

代码片段:
using System.Web
// others code...
// others code...
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Write();

同样: ASP.net报错误:The name 'Server' does not exist in the current context. / 当前上下文中不存在名称'Server'时可以使用System.Web.HttpContext.Current.Server来代替,既:

using System.Web
// others code...
// others code...
HttpContext.Current.Server.MapPath("~/");


另外补充: 在原因分析里已经阐述,明确的是:如果可以使用Response对象,那么该类一定继承了System.Web.UI.Page类,否则会报编译错误,既上述的错误。但是反过来,如果一个类已经继承了System.Web.UI.Page类,那么这个类中一定可以用Response对象吗,比如我们新建一个class,并且让这个class继承Page类之后使用Response对象,示例代码如下:
在自动生成的TestResponse.aspx.cs文件中代码,这种coding不会出现编译和运行错误:

public partial class TestResponse : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e){
Response.Write("Run >>> Page_Load()");
}
}

直接创建一个普通的class即VerifyModel.cs文件,并且让该类继承System.Web.UI.Page,运行会怎样呢:

public class VerifyModel : System.Web.UI.Page
{
public void VerifyDefaultResponse(){
Response.Write("Run >>> VerifyLogin()");
}
}
首先我们要clear的是我们直接使用Response对象时,或者说使用Response.Write("XXX")的时候一定是在ASP页面XXX.aspx里code-Behind分离出来的一个类,既XXX.aspx.cs中使用,而该类默认便继承了Page类;但如果在其他地方直接创建一个class,并且该class继承了page类,调用Reponse对象中的方法:首先不会出现编译错误,但是如果运行,他仍然会出异常:[System.Web.HttpException],一般Page的实例都不应该由用户创建。ASP.net创建Page后,会调用它的一个内部的方法ProcessRequest并且把HttpContext传进去的。你越过此步当然不行了。
应该修改为:
public class VerifyModel : System.Web.UI.Page
{
public void VerifyHttpResponse(){
HttpContext.Current.Response.Write("Run >>> VerifyHttpResponse()");
}
}

参考资料

flyaim,《ASP.NET出错-当前上下文中不存在名称"Response"》 : http://blog.csdn.net/flyaim/article/details/5372304 greatabel,《response.write响应在此上下文中不可用》 :http://blog.sina.com.cn/s/blog_535d25720100f8bp.html
问道者,《在非XXX.aspx.cs文件中使用Response、Request对象》 :http://www.cnblogs.com/webflash/archive/2009/07/06/1517679.html
Edison Chou,《ASP.Net请求处理机制初步探索之旅 - Part 2 核心》 :http://www.cnblogs.com/edisonchou/p/4195259.html

注:本文原创由`bluetata`发布于blog.csdn.net、转载请务必注明出处。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐