【问题标题】:Server.Transfer losing local variablesServer.Transfer 丢失局部变量
【发布时间】:2011-10-26 17:16:45
【问题描述】:

对于我的应用程序,我有一个页面通过Server.Transfer 重定向到另一个页面(在同一应用程序中)。我需要这样做,因为原始页面有一个我需要使用 Page.PreviousPage 属性访问的对象。

一旦我的“目标”页面完全加载,当我执行回发时,我对源页面对象制作的本地深度克隆会突然从内存中释放?这是设计使然 - 与 Server.Transfer 有关吗?

一个例子...

Page1.aspx:

Public Structure myCustomObject
    Implements ICloneable
    Dim someField as String = "default value" ' Default value
    Public Function Clone() As Object Implements System.ICloneable.Clone
        Dim temp as new myCustomObject
        temp.someField = Me.someField
        Return temp
    End Function
End Structure

Dim obj As myCustomObject
Public ReadOnly Property objProp as myCustomObject
    Get
        Return obj
    End Get
End Property
objProp.someField = "changed value from source page"

Server.Transfer("page2.aspx", True)

Page2.aspx:

(onLoad)
Dim newObj As myCustomObject
newObj = Page.PreviousPage.objProp.Clone()
Debug.Write(newObj.someField) ' Output: "changed value from source page"

此时,一切正常。东西被正确克隆了,一切都很好。

(Let's say this is on a button click event)
Debug.Write(newObj.someField) ' Output: "default value"<- This is NOT "changed value from source page" for some reason when it was working literally a few lines ago!

问题就在这里。我的猜测是 Server.Transfer 在新页面加载后停止与源页面的任何关联。

有没有更好的跨页面对象传递方式?

【问题讨论】:

  • 如果您在该页面上放置一个按钮和服务器端点击,您可以从点击事件中访问您的对象吗?你能显示一些代码吗?
  • 我说的可能有点不清楚,但我不知道有什么其他的说法。
  • 这对我来说很难闻。您当然可以将原始对象存储在其他容器中,然后在重定向页面的页面加载中将其拉回?
  • @Graham 我认为这就是问题所在。我不确定哪种“容器”最适合我的需要。

标签: asp.net vb.net


【解决方案1】:

只需在HttpContext 中传递一个变量,您将不得不处理您的转换,不确定Page.PreviousPage 是什么:

当前页面:

HttpContext CurrContext = HttpContext.Current;
CurrContext.Items.Add("PreviousPage", Page.PreviousPage);

转移到页面:

HttpContext CurrContext = HttpContext.Current;
var previousPage = CurrContext.Items["PreviousPage"];

对不起 C#,我回答时没有代码,而且问题没有用 VB.NET 标记。有人可以随意转换。

【讨论】:

  • 这适用于对象吗?如果我走这条路线,我不需要序列化吗?
  • Server.Transfer 不是新请求,你还在服务器上,不需要序列化。 HttpContext.Items 只是一个字典。
  • 我刚刚测试了你的方法,它给我的结果和我的例子一样。不知何故,当我执行回发时,转移到页面的 HttpContext.Current 不记得我从当前页面添加的内容。
  • 尝试传递一个字符串测试值“foo”,它消失了吗?
  • 是的。不知道会是什么。
【解决方案2】:

如果有人仍在寻找此问题的解决方案,则很可能是您的 RouteConfig.cs 中的 settings.AutoRedirectMode = RedirectMode.Permanent; 设置。改成settings.AutoRedirectMode = RedirectMode.Off;

 public static void RegisterRoutes(RouteCollection routes)
    {
        var settings = new FriendlyUrlSettings();
        //  settings.AutoRedirectMode = RedirectMode.Permanent;
        settings.AutoRedirectMode = RedirectMode.Off;
        routes.EnableFriendlyUrls(settings);
    }

【讨论】:

    猜你喜欢
    • 2016-09-02
    • 2012-07-30
    • 2016-06-04
    • 1970-01-01
    • 2011-09-30
    • 1970-01-01
    • 2012-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多