【问题标题】:Not getting my Roles from my SQL Server database through C#没有通过 C# 从我的 SQL Server 数据库中获取我的角色
【发布时间】:2020-02-28 16:43:31
【问题描述】:

我正在尝试构建一个应用程序,通过登录用户 Dll 导入功能验证您在 Windows 上的登录。我让它工作了,但现在我想添加让用户通过我的 SQL 数据库进行身份验证并赋予角色的能力。例如,用户登录并从 SQL 接收角色并获得登录用户的授权。该角色按重要性顺序为管理员、管理、用户。不太确定出了什么问题。任何帮助,将不胜感激。

这是我的 C# 代码

FormsAuthentication.Initialize();
string roles = string.Empty;
var conn = @"Data Source = localhost;Initial Catalog=web";

using (var con = new SqlConnection(conn))
{
    using (SqlCommand cmd = new SqlCommand("Get_User_Role"))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@Username", btnLogin);

        cmd.Connection = con;

        con.Open();

        SqlDataReader reader = cmd.ExecuteReader();
        reader.Read();
        roles = reader["Roles"].ToString();
        con.Close();
    }
}

这是我的web.config

<authentication mode="Forms">
      <forms loginUrl="login.aspx" name=".ASPXAUTH" protection="All" path="/" defaultUrl="Default.aspx" timeout="30" ></forms>
</authentication>
<authorization>
      <deny users="?"/>
      <allow roles="Administrators, Managers,Users"/>
      <allow users="*"/> <!-- might have to delete this to work, which is ok. Better to have and not need then to need and not have. -->
</authorization>

这是我从 ASP 登录的按钮

<asp:Button ID="btnLogin" runat="server" width="315px" Cssclass="btn" 
            onclick="btnLogin_Click" Text="Login" ></asp:Button>

我运行它,它停在con.Open 说用户名不正确。

我还被告知我需要为管理员、经理、用户添加一个列表。我不应该对roles=reader["Roles"].ToString(); 感到厌烦,对吧?

【问题讨论】:

  • 您的连接字符串ConnectionString / More Details 似乎有问题
  • 我们还需要表的架构。
  • @JonathanAlfaro 我现在就编辑它。我还应该包含 LOGON 用户代码吗?我做了一个存储过程,这样它就不会直接访问表。需要查看存储过程架构?
  • 在文本中显示“管理员、经理、用户”,但在 web.config 中显示“管理员、管理员、用户”(即复数形式)。我想这只是文本中的一个错字。
  • 存储过程的代码是什么?我有点担心您的设计:您将系统登录与角色的 sql 服务器表混合在一起......我会选择一种方式或另一种方式。 Windows 用户可以按组进行组织,而无需与数据库相关联。另一方面,有很多基于完整数据库的身份验证/授权的解决方案(请参阅 ASP.NET Identity)。

标签: c# asp.net sql-server asp.net-mvc


【解决方案1】:

我运行它,它在 con.Open 处停止,说用户名不正确。

您的连接字符串有问题,请检查以下链接:

Microsoft Documentation

Examples

FormsAuthentication.Initialize();
string roles = string.Empty;
var conn = @"Data Source = localhost;Initial Catalog=web"; // Here your problem

using (var con = new SqlConnection(conn))
{
    using (SqlCommand cmd = new SqlCommand("Get_User_Role"))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@Username", btnLogin);

        cmd.Connection = con;

        con.Open();

        SqlDataReader reader = cmd.ExecuteReader();
        reader.Read();
        roles = reader["Roles"].ToString();
        con.Close();
    }
}

【讨论】:

  • 是的,正确的语法是var conn = @"Server=MyserverHeret;Database=MyDatabaseHere;Trusted_Connection=True;"; 这让我可以访问我的服务器。谢谢
猜你喜欢
  • 2010-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-30
  • 2023-03-03
相关资源
最近更新 更多