2

在 C# 中使用 Visual Studio 2010 .NET Framework 4.0。

每次我尝试使用重定向时response.redirect("url")都会收到以下错误:

System.NullReferenceException was unhandled by user code
  Message=Object reference not set to an instance of an object.
  Source=App_Web_uck3gvsb
  StackTrace:
       at _Default.Page_Load(Object sender, EventArgs e) in c:\inetpub\wwwroot\p1\Default.aspx.cs:line 15
       at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
       at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
       at System.Web.UI.Control.OnLoad(EventArgs e)
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  InnerException: 

这是代码:即使在没有任何东西的简单上,我也会遇到同样的错误!

using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    public  HttpResponse response;
    protected void Page_Load(object sender, EventArgs e)
    {

        response.Redirect("http://www.google.com");
    }
}
4

3 回答 3

6

你应该使用:

Response.Redirect("www.bing.com");

不是:

response.Redirect("...")
于 2012-12-03T16:55:34.600 回答
2

您需要利用Page.Response属性:

Page.Response.Redirect(...);

要不就

Response.Redirect(...);

当你声明你的HttpResponse对象时,它没有被初始化,因此null. 这就是异常的原因。

于 2012-12-03T16:52:56.797 回答
2

注释掉你public HttpResponse response;声明了一个unnecessary未初始化的变量。

public partial class _Default : System.Web.UI.Page
{
    //public  HttpResponse response;
    protected void Page_Load(object sender, EventArgs e)
    {
        //this is enough
        Response.Redirect("http://www.google.com");
    }
}
于 2012-12-03T16:53:34.333 回答