使用角色(Web 表单)登录不起作用



我想在 Web 表单中创建具有 3 个角色 asp.net 身份验证模块。我创建了一个包含表用户(id、登录名、密码、角色)的简单数据库。我有 3 个角色:用户、用户 2 和管理员。我想将具有特定角色的用户重定向到各个页面。

登录.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
namespace WebApplication6
{
    public partial class Login : System.Web.UI.Page
    {
        static string DatabaseConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["dbtestConnectionStrings"].ConnectionString;
        SqlConnection _connection= new SqlConnection(DatabaseConnectionString);

    protected void Page_Load(object sender, EventArgs e) { 
    }
    protected void LoginButton_Click(object sender, EventArgs e)
    {
        try
        {
            var comm = new SqlCommand("select * from user where login=@login and password=@password", _connection);
            comm.Parameters.AddWithValue("@login", LoginUser.UserName);
            comm.Parameters.AddWithValue("@password", LoginUser.Password);
            _connection.Open();
            var rd = comm.ExecuteReader(); 
            if (rd.HasRows)
            {
                while (rd.Read())
                {
                    Session["UserName"] = rd["login"].ToString();
                    string role = rd["role"].ToString();
                    if (role == "user") Response.Redirect("User/User.aspx");
                    else if (role == "user2") Response.Redirect("User2/User.aspx");
                    else Response.Redirect("Admin/Admin.aspx"); 
                }
            }
            else
            {
                LoginUser.FailureText = "ERROR";
            }
        }
        catch (Exception exception)
        {
            Response.Write(exception.StackTrace);
        }
        }         
    }
}

结果:

网络.config

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
    </httpModules>
  </system.web>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=&quot;Web&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules>
      <remove name="ApplicationInsightsWebTracking" />
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
    </modules>
  </system.webServer>
  <appSettings>
    <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
  </appSettings>
  <connectionStrings>
    <add name="dbtestEntities" connectionString="metadata=res://*/DataModel.csdl|res://*/DataModel.ssdl|res://*/DataModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=ROG-KOMPUTERSQLEXPRESS;initial catalog=dbtest;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;"
      providerName="System.Data.EntityClient" />
    <add name="dbtestConnectionString" connectionString="Data Source=ROG-KOMPUTERSQLEXPRESS;Initial Catalog=dbtest;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

可以看到两个缺陷

  1. 用户是一个关键字,您将其用作表名
  2. 分配参数值时,您正在指定@

尝试以下代码

protected void LoginButton_Click(object sender, EventArgs e)
    {
        try
        {
            SqlCommand comm = new SqlCommand("select login,role from [user] where login=@login and password=@password", _connection);
            comm.Parameters.AddWithValue("@login", LoginUser.UserName);
            comm.Parameters.AddWithValue("@password", LoginUser.Password);
            _connection.Open();
            SqlDataReader rd = comm.ExecuteReader(); 
            if (rd.HasRows)
            {
                while (rd.Read())
                {
                    Session["UserName"] = rd[0].ToString();
                    string role = rd[1].ToString();
                    if (role == "user") Response.Redirect("User/User.aspx");
                    else if (role == "user2") Response.Redirect("User2/User.aspx");
                    else Response.Redirect("Admin/Admin.aspx"); 
                }
            }
            else
            {
                LoginUser.FailureText = "ERROR";
            }
rd.Close();
_connection.Close();
        }
        catch (Exception exception)
        {
            Response.Write(exception.StackTrace);
        }
        }

它看起来像这样:

protected void LoginButton_Click(object sender, EventArgs e)
        {
            try
            {
                var comm = new SqlCommand("select login,role from [user] where login=@login and password=@password", _connection);
                comm.Parameters.AddWithValue("@login", LoginUser.UserName);
                comm.Parameters.AddWithValue("@password", LoginUser.Password);
                _connection.Open();
                SqlDataReader rd = comm.ExecuteReader();
                if (rd.HasRows)
                {
                    while (rd.Read())
                    {
                        Session["UserName"] = rd[0].ToString();
                        string role = rd[1].ToString();
                        if (role == "user") Response.Redirect("User/User.aspx");
                        else if (role == "user2") Response.Redirect("User2/User.aspx");
                        else Response.Redirect("Admin/Admin.aspx");

                    }
                }

                else
                {
                    LoginUser.FailureText = "ERROR";
                }
                rd.Close();
                _connection.Close();
            }
            catch (Exception exception)
            {
                Response.Write(exception.StackTrace);
                Label1.Text = exception.Message;
            }
        }

最新更新