3

请帮忙!!我正在使用 Visual Studio,在 ASP.NET C# (.Net 4) 中编程:我是一名 PHP 转换者,试图使用会话创建一个简单的登录页面。看到我是 ASP.NET 的新手,我从互联网上的某个地方使用了这段代码:

登录.aspx:

<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
<asp:Button ID="submit" runat="server" Text="Submit" onclick="submit_Click" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

登录.aspx.cs:

protected void send_Click(object sender, EventArgs e)
        {
        if (txtUserName.Text == "admin" && txtPassword.Text == "admin")
        {
            Session["Authenticate"] = "Yes";
            Response.Redirect("Default.aspx");
        }
        else
            Label1.Text = "Login failed";
        }

全球.asax.cs

void Session_Start(object sender, EventArgs e)
    {
        // Code that runs when a new session is started
        Session["Authenticate"] = "";
        CheckLogin();
    }
void Application_OnPostRequestHandlerExecute()
    {
        CheckLogin();
    }

    void CheckLogin()
    {
        string Url = Request.RawUrl;
        int count = Url.Length - 10;
        string TestUrl = Url.Substring(count);
        string SessionData = Session["Authenticate"].ToString();
        if (SessionData == "" && TestUrl != "Login.aspx")
        {
            Response.Redirect("~/Login.aspx");
        }
    }

每当我尝试在浏览器中运行此代码时,我的 CSS 文件都不会加载。这似乎链接到 global.asax 文件,因为如果我注释掉上面在我的 global.asax.cs 片段中显示的所有代码,css 会正确加载。

我曾尝试通过源代码在浏览器中打开 css 文件,但出现以下错误:

Session state is not available in this context.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Web.HttpException: Session state is not available in this context.

Source Error: 


Line 45:             int count = Url.Length - 10;
Line 46:             string TestUrl = Url.Substring(count);
Line 47:             string SessionData = Session["Authenticate"].ToString();
Line 48:             if (SessionData == "" && TestUrl != "Login.aspx")
Line 49:             {

Source File: D:\MyTestWebsite\Global.asax.cs    Line: 47 

我也尝试过使用 App_Themes 使用主题并在 Web.config 中定义它 - 给出了同样的问题。css 仅在删除与会话相关的代码时显示。

Any idea what's causing this???

4

1 回答 1

1

The issue is that you're checking login when attempting to load your static resources as well as dynamic pages. Certain files (such as global CSS) should be available for full anonymous access and not gated behind authentication logic.

You are definitely reinventing the wheel as the built in Forms Authentication supported by a large library of membership providers provide a rich base for you to expand upon. If you do choose to go forward with this method, my suggestion would be to query the requested file and ensure that they are requesting an aspx (assuming you are not using url rewriting) before requiring authentication.

于 2012-07-11T12:42:39.800 回答