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?
1 Answer 1
You need to take care of Single Responsibility Principle here. Your Post method should handle only HTTP request and then it passes to another handler for further operation and after receiving the result, revert back to User.
You can follow SRP and DRY principle in your code.
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\$