简体   繁体   中英

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. But actually I obtain an null value. To obtain the role I have an stored procedure with output parameter.

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.

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.

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

But I'm getting the error on that line:

System.Web.SessionState.HttpSessionState.this[string].get returned 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. 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 .

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:
ExecuteScalar will get the @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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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