我已经继承了一个项目,该项目使用以下模式将代码后面的参数传递给aspx页面。我知道这是错误的,但是我正在重构最佳方式。你会如何重构页面成员的ASPX代码?
代码背后:
using System;
using System.Web;
namespace BadPassing
{
public partial class _Default : System.Web.UI.Page
{
private Random rnd = new Random(); //Is this bad?
protected int numberOne; //this is bad
protected int numberTwo; //this is bad
protected void Page_Load(object sender, EventArgs e)
{
numberOne = rnd.Next(100);
numberTwo = rnd.Next(100);
}
}
}
ASPX页面:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="BadPassing._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Bad Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<a href="http://www.google.com/search?q=<%=this.numberOne %>%2B<%=this.numberTwo %>">
Add <%=this.numberOne %> and <%=this.numberTwo %> using google.
</a>
</div>
</form>
</body>
</html>
我的理解是,的Numberone和numberTwo不是线程安全的,并可能导致不正确的行为,如果两个人在加载页面时同一时间。此外,如果页面依赖于numberOne和numberTwo在回发之间存储值,则多个同时发生的用户将导致意外的结果。
我的理解是为什么上述技术如此糟糕是正确的,如果是的话,您会如何最好地重构此代码?
请注意,将无状态页面级服务(如随机)存储为页面类的成员变量是不正确的?
谢谢。我完全误解了ASPX渲染周期。这很明显。 – 2009-01-08 04:08:48