I have a post method in an WebAPI2 controller. I just want to make sure that everything I have done is correct. I want to create a new task run the method asynchronously and return a message.
public async Task<IHttpActionResult> Post([FromBody]Menu m)
{
using (MySqlConnection con = new MySqlConnection(""))
using (MySqlCommand cmd = new MySqlCommand("Insert into Menu (Description,LanguageId,IsActive) values (@Description,@LanguageId,@IsActive) ", con))
{
try
{
if (con.State == ConnectionState.Closed)
{
await con.OpenAsync();
cmd.Parameters.AddWithValue("@Description", m.Description);
cmd.Parameters.AddWithValue("@LanguageId", m.LanguageId);
cmd.Parameters.AddWithValue("@IsActive", m.IsActive);
await cmd.ExecuteNonQueryAsync();
}
}
catch (MySqlException ex)
{
return Content(HttpStatusCode.NotFound,ex);
}
finally
{
await con.CloseAsync();
}
return Ok("Inserted Succesfully");
}
}
Should I create a new async method to execute the query and then return the message into the post method of the controller, or is this the correct way?
if (con.State == Connection.Closed)
is. You just created the object a few lines prior, so it should of course be closed. Similarlycon.CloseAsync()
shouldn't be necessary as exiting theusing
block should dispose (by closing) the database connection. \$\endgroup\$