我正在尝试构建一个通过“登录用户Dll导入”功能验证Windows登录的应用程序。我可以使用它,但是现在我想添加通过我的SQL数据库对用户进行身份验证并赋予角色的功能。例如,用户登录并从SQL接收角色,并获得登录用户的授权。该角色按重要性顺序是Administrator,Management,User。不太确定出什么问题了。任何帮助,将不胜感激。
这是我的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();
吗?
我运行它,它停在con.Open上,说用户名不正确。
您的连接字符串有问题,请检查以下链接:
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();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句