1

全部,

我只是想知道是否有一种逻辑方法可以在每次页面加载时不重新分配变量 pageCount,但仍然没有得到未命名的变量 YSOD 屏幕。

我试图在每次加载页面时增加 pageCount,以便我可以强制“history.go(pageCount * -1)”(在 JavaScript 中)。

如果我通常将 pageCount 分配为 0(例如 int pageCount = 0;),它会在每次页面加载时将其重置为 0,但如果我在分支中对其进行初始化,则它超出了绘制的隐藏输入字段值的范围在 C# 中(让 JavaScript 在另一边接受)。

我已经尝试过 AppState 但它不喜欢作为 int (或 bool )工作,即使我尝试将它转换为:

(int)AppState["pageCount"];

关于如何将全局(因为缺少更好的词)变量声明为 int 或 bool 的任何建议,或者可能应用逻辑来声明不会在每次页面加载时重置为其初始化值的常规变量?

var username = "";
var user = "";
var password = "";
var errorMessage = "";
var loginSuccess = "not";
AppState["gActionMessage"] = "";
int pageCount;
if(!IsPost)
{
    pageCount = 1;
}
if(IsPost)
{
    pageCount++;
    username = Request.Form["username"];
    password = Request.Form["password"];

    if(username.IsEmpty() || password.IsEmpty())
    {
        errorMessage = "You must specify both a username and password.";
    }
    else
    {
        if (WebSecurity.UserExists(username) && WebSecurity.GetPasswordFailuresSinceLastSuccess(username) > 4 && WebSecurity.GetLastPasswordFailureDate(username).AddSeconds(120) > DateTime.UtcNow) {
            AppState["gActionMessage"] = "You're account has been locked due to too many failed login attempts. " +
                                        "Please try again in 2 minutes.";
            AppState["gActionMessageDisplayed"] = "not";
            Response.Redirect("~/");
            return;
        }

        if(WebSecurity.Login(username, password, false))
        {
            var db = Database.Open("Users");
            user = (db.QuerySingle("SELECT firstName FROM UserProfile WHERE LOWER(Email) = LOWER(@0)", username)).firstName;

            AppState["gActionMessage"] = "Hello, " + user + "!";
            AppState["gActionMessageDisplayed"] = "not";
            loginSuccess = "is";
            //Response.Redirect("~/");
        }
        else
        {
            errorMessage = "Login failed. Please check your user name and password for errors.";
            loginSuccess = "not";
        }
    }
}

由于 pageCount 未分配,上述代码在第 7 行出现错误。

谢谢你的帮助!

4

1 回答 1

2

AppState集合是object引用的集合。要存储intorbool值,它将被装箱。

要阅读它,您只需将其拆箱,就像您尝试过的那样。但是,如果您不知道它是否已经设置,则必须将其作为对象引用并检查是否有引用。一旦你检查了你确实有一个参考,你可以取消装箱值:

int pageCount;
object p = AppState["pageCount"];
if (p != null) {
  pageCount = (int)p;
} else {
  pageCount = 1; // some default value that you want to use
}
于 2012-10-16T20:56:45.993 回答