简体   繁体   English

如何使用 C# 从 SQL 服务器获取参数 output 并将值放入 Z21D6F2440CFB5121982E4 变量中

[英]How to get a parameter output from SQL Server with C# and put the value in a session variable

I'm trying to obtain the user role from a select in SQL Server for blocking some pages depending on a session value.我正在尝试从 SQL 服务器中的 select 获取用户角色,以根据 session 值阻止某些页面。 But actually I obtain an null value.但实际上我获得了一个 null 值。 To obtain the role I have an stored procedure with output parameter.为了获得角色,我有一个带有 output 参数的存储过程。

CREATE PROCEDURE obtenerROl 
     @user varchar(20), 
     @passwrd varchar(20), 
     @rol tinyint OUTPUT
AS
BEGIN
    SELECT @rol = idROl 
    FROM Users 
    WHERE nameUSer = @user AND password = @passwrd 

    RETURN @rol
END

In the login.aspx.cs page I try to retrieve the value for the output parameter and put in on a session variable.login.aspx.cs页面中,我尝试检索 output 参数的值并输入 session 变量。

public void obtenerRol()
{
    using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connDb"].ConnectionString))
    {
        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "obtenerROl";

        cmd.Parameters.Add("@user", SqlDbType.VarChar).Value = txtUsuario.Text.Trim();
        cmd.Parameters.Add("@passwrd ", SqlDbType.VarChar).Value = txtContraseña.Text.Trim();
        SqlParameter rol = new SqlParameter("@rol", SqlDbType.TinyInt);
        rol.Direction = ParameterDirection.Output;
        cmd.Parameters.Add(rol);

        cmd.Connection = conn;
        cmd.ExecuteReader(CommandBehavior.CloseConnection); 

        conn.Open();                    
        Session["UserRole"] = cmd.Parameters["@rol"].Value.ToString();
    }
}

After the login, in the main page I have a label just for checking the value of the session.登录后,在主页上我有一个 label 仅用于检查 session 的值。

 mensajeID.Text = Session["UserRole"].ToString();

But I'm getting the error on that line:但我在那条线上遇到了错误:

System.Web.SessionState.HttpSessionState.this[string].get returned null. System.Web.SessionState.HttpSessionState.this[string].get 返回 null。

So I'm guessing the method is not working well.所以我猜这个方法效果不好。

The last line I added was我添加的最后一行是

cmd.ExecuteReader(CommandBehavior.CloseConnection);

because I read that is necessary to close the datareader to process the output parameters, but it didn't work.因为我读到必须关闭数据读取器才能处理 output 参数,但它不起作用。 I hope you can help me with my problem, regards.我希望你能帮助我解决我的问题,问候。

Hi I can only post code here and this would be the way I wrote it (couldn't test it):嗨,我只能在这里发布代码,这就是我编写它的方式(无法测试):

I assume your default db schema is dbo => dbo.obtenerROl .我假设您的默认数据库架构是dbo => dbo.obtenerROl

public void obtenerRol()
    {
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connDb"].ConnectionString))
        using (SqlCommand cmd = new SqlCommand("dbo.obtenerROl", conn))
        {
            cmd.CommandType = CommandType.StoredProcedure;


            cmd.Parameters.Add("@user", SqlDbType.VarChar).Value = txtUsuario.Text.Trim();
            cmd.Parameters.Add("@passwrd ", SqlDbType.VarChar).Value = txtContraseña.Text.Trim();
            SqlParameter rol = new SqlParameter("@rol", SqlDbType.TinyInt);
            rol.Direction = ParameterDirection.Output;
            cmd.Parameters.Add(rol);

            conn.Open();
            cmd.ExecuteNonQuery();

            //according to https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/linq/sql-clr-type-mapping
            byte userRole = (byte) cmd.Parameters["@rol"].Value;
            Session["UserRole"] = userRole;

            conn.Close();
        }
    }

and

CREATE PROCEDURE obtenerROl 
   @user varchar(20), 
   @passwrd varchar(20), 
   @rol tinyint OUTPUT
AS
BEGIN
   SELECT @rol = idROl 
   FROM Users 
   WHERE nameUSer = @user AND password = @passwrd 

   RETURN 0; -- for success
END

you could also你也可以

CREATE PROCEDURE obtenerROl 
    @user varchar(20), 
    @passwrd varchar(20)
AS
BEGIN
   DECLARE @rol tinyint = 0; -- default role
   SELECT @rol = idROl 
   FROM Users 
   WHERE nameUSer = @user AND password = @passwrd;

   SELECT @rol;
END

and your C# Code:和您的 C# 代码:
ExecuteScalar will get the @rol. ExecuteScalar 将获得@rol。

public void obtenerRol()
{
    using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connDb"].ConnectionString))
    using (SqlCommand cmd = new SqlCommand("dbo.obtenerROl", conn))
    {
        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.Add("@user", SqlDbType.VarChar).Value = txtUsuario.Text.Trim();
        cmd.Parameters.Add("@passwrd ", SqlDbType.VarChar).Value = txtContraseña.Text.Trim();

        conn.Open();
        var value = cmd.ExecuteScalar();

        //according to https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/linq/sql-clr-type-mapping
        byte userRole = (byte)value;
        Session["UserRole"] = userRole;

        conn.Close();
    }
}

To be complete:要完整:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM