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.