随机数不更新

时间:2014-11-10 14:30:22

标签: c# asp.net

我有以下代码查看xml文件并尝试随机选择一个值,但我似乎无法弄清楚它为什么不起作用。它一直选择相同的项目,只有刷新页面超过100次才更新数字 - 任何人都看到下面的代码有问题?

static Random random = new Random();

private void GenerateRandomCode()
{
    string path = base.Request.PhysicalApplicationPath + @"\App_Data\captchaconfig.xml";

    try
    {
        XmlDocument document = new XmlDocument();
        document.LoadXml(File.ReadAllText(path));
        XmlNodeList list = document.SelectNodes("/codes/code");
        XmlNode node = list[random.Next(0, list.Count - 1)];
        txtHidden.Value = node.Attributes["id"].Value;
    }
    catch
    {
        // Do something
    }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (string.IsNullOrEmpty(txtHidden.Value))
    {
        GenerateRandomCode();
    }


    if (!Page.IsPostBack)
    {
        // Do something, nothing to do with GenerateRandomCode()
    }
}

我在此方法之外创建了Random()的新实例,在此示例中,我将其称为random

更新

好的,我已经对上面的代码示例进行了一些更新,以尝试回答您的一些问题。我还制作了random,结果仍然相同。

XML的一个例子如下:

<?xml version="1.0" encoding="iso-8859-1"?>
<codes>
  <code id="0">570582</code>
  <code id="1">307157</code>
  <code id="2">588869</code>
  <code id="3">994165</code>
  <code id="4">126340</code>
  <code id="5">324903</code>
  <code id="6">644656</code>
  <code id="7">537704</code>
  <code id="8">344852</code>
  <code id="9">730435</code>
  .
  .
  .
  <code id="299">711202</code>
</codes>

1 个答案:

答案 0 :(得分:0)

感谢大家对此的帮助,问题是该页面正在被缓存。我查看了Web服务器上的物理页面,并在顶部注意到了这一点:

<%@ OutputCache CacheProfile="Full" %>

删除此功能解决了问题。