asp.net c# ExecuteReader() error
-
05-02-2021 - |
Question
The following code produces an error. dbo.getit works fine when I call it directly on the server. The error occurs at cmd.ExecuteReader() . What am I doing wrong?
string user;
string pw;
SqlDataReader dr = null;
SqlConnection conn = new SqlConnection("Data Source=xxx;Initial Catalog=myDB; Integrated Security=True");
user = Username.Text.Trim();
pw = Password.Text.Trim();
conn.Open();
try {
SqlCommand cmd = new SqlCommand("dbo.getit", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@param1", user);
cmd.Parameters.AddWithValue("@param2", pw);
dr = cmd.ExecuteReader();
while ( dr.Read() )
{
Session["username"] = user;
// Session["admin"] =
// Session["completed"] =
Server.Transfer("all_is_well.aspx");
}
conn.Close();
conn.Dispose();
} catch (Exception ex) {
if (dr != null)
{
dr.Close();
conn.Close();
}
Server.Transfer("ERROR.aspx");
}
SOLUTION: Replace the two corresponding lines above with these:
SqlCommand cmd = new SqlCommand("select * from dbo.getit(@param1, @param2);", conn);
cmd.CommandType = CommandType.text;
Solution 3
SOLUTION: Replace the two corresponding lines above with these:
SqlCommand cmd = new SqlCommand("select * from dbo.getit(@param1, @param2);", conn);
cmd.CommandType = CommandType.text;
That worked.
OTHER TIPS
This just seems questionable,
Session["username"] = user;
Server.Transfer("all_is_well.aspx");
inside the while loop!
Can you at least finish iterating on the reader, using a temporary object to store the result of the query, and then initialize you session and do the Server.Transfer
. .
Server.Transfer terminates execution of the current page and starts execution of a new page for the current request. Also, Transfer calls End, which throws a ThreadAbortException exception upon completion.
I think what you are trying to do (and I am answering based on what you are trying to do - not necessarily best pratice) is verify that the user is authorized/authenticated in some way based on a data store. You'd be better off not using ExecuteReader at all. Use ExecuteScalar. If the result of ExecuteScalar is not null, the user was found.
if (cmd.ExecuteScalar() != null)
{
Server.Transfer("all_is_well.aspx");
}
else
{
Server.Transfer("someErrorPage.aspx");
}