2016-04-27 86 views
1

我想在asp.net web表单中创建包含3个角色的验证模块。 我创建了一个具有一个表用户(id,登录名,密码,角色)的简单数据库。 我有3个角色:用户,用户2和管理员。 我想将具有特定角色的用户重定向到单个页面。不能正常工作登录角色(网络表单)

Login.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 [email protected] and [email protected]", _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); 
     } 
     }   
    } 
} 

Result:

的web.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-KOMPUTER\SQLEXPRESS;initial catalog=dbtest;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" 
     providerName="System.Data.EntityClient" /> 
    <add name="dbtestConnectionString" connectionString="Data Source=ROG-KOMPUTER\SQLEXPRESS;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> 
+0

没有ü尝试调试?发生了什么......任何错误? – Sachu

+0

你的连接出错。请检查连接字符串 – Sachu

+0

在服务器资源管理器中,我有数据连接 - > dbtestConnectionString。在修改连接是按钮测试连接:“测试连接成功”。 如果需要,我可以显示我的web.config。 – Risksec7

回答

2

可以看到两个缺陷

  1. 用户是一个关键字,您使用的是作为表名
  2. 在分配参数值,你specifiying @

试试下面的代码

protected void LoginButton_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      SqlCommand comm = new SqlCommand("select login,role from [user] where [email protected] and [email protected]", _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); 
     } 
     } 
+0

现在它的工作,但我输入登录名和密码的一切重定向到Admin.aspx – Risksec7

+0

你可以发布表列的名称和值? – Sachu

+0

列:ID,登录名,密码,角色。 值:1,用户,通过,用户; 2,用户2,PASS2,用户2; 3,admin,pass,admin – Risksec7

0

它看起来像:

protected void LoginButton_Click(object sender, EventArgs e) 
     { 
      try 
      { 
       var comm = new SqlCommand("select login,role from [user] where [email protected] and [email protected]", _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; 
      } 
     } 
+0

不添加你的代码作为answer.edit的问题,并张贴在那里..还有在参数仍然可以看到'@'..它不是像我在回答中提到 – Sachu

+0

与'@',没有这个结果是一样的 任何想法? – Risksec7

+0

它应该与@ ..没有错在代码..有些数据问题似乎 – Sachu