Parameterized query, parameter not passed Error, only on Win 11 asp.net Web Api

89 Views Asked by At

The web Api works 100% on windows 10 but as soon as I run it on a windows 11 machine it doesn't work.

The error I get. System.Data.SqlClient.SqlException (0x80131904): The parameterized query '(@UserName nvarchar(4000))SELECT * FROM User_Table WHERE @UserNa' expects the parameter '@UserName', which was not supplied.

Asp is running .net6.0. When The same web api is running on a win 10 machine its smooth and fast with no problems. The windows 11 is up to date I tried updating it right before I Wrote this post so that isn't the problem. This post is my last resort as I can't find the same problem online. I am testing it using Postman.

The Code

[HttpPost]
        public IActionResult post([FromBody] User user)
        {
            string query = "INSERT INTO User_Table (ut_User, ut_UserCode, ut_Branch) VALUES (@UserName, @UserCode, @Branch)";
            string query2 = "SELECT * FROM User_Table WHERE @UserName = ut_User";
            string sqlDataSource = _configuration.GetConnectionString("IMSConnStr");

            using (SqlConnection mycon = new SqlConnection(sqlDataSource))
            {
                mycon.Open();
                using (SqlCommand cmd = new SqlCommand(query2, mycon))
                {
                    cmd.Parameters.AddWithValue("@UserName", user.UserName);
                    SqlDataReader reader = cmd.ExecuteReader();
                    if (reader.HasRows) return Ok(200);
                }
            }
            using (SqlConnection mycon = new SqlConnection(sqlDataSource))
            {
                mycon.Open();
                using (SqlCommand cmd = new SqlCommand(query, mycon))
                {
                    cmd.Parameters.AddWithValue("@UserName", user.UserName);
                    cmd.Parameters.AddWithValue("@UserCode", user.UserCode);
                    cmd.Parameters.AddWithValue("@Branch", user.Branch);
                    cmd.ExecuteNonQuery();
                }
                mycon.Close();
            }

            return Ok(200);
        }
    }

I Have tried Changing the FromBody to FromForm but then I Get a 415 Unsupported Media Type error. I Have also tried to specifically set Content-Type to application/json, which didn't change anything.

0

There are 0 best solutions below