0
\$\begingroup\$

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?

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Sep 2, 2017 at 21:01
\$\endgroup\$
1
  • 2
    \$\begingroup\$ I'm not sure what the purpose of if (con.State == Connection.Closed) is. You just created the object a few lines prior, so it should of course be closed. Similarly con.CloseAsync() shouldn't be necessary as exiting the using block should dispose (by closing) the database connection. \$\endgroup\$ Commented May 7, 2018 at 14:38

1 Answer 1

1
\$\begingroup\$

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.

Jesse C. Slicer
14.5k1 gold badge40 silver badges54 bronze badges
answered Sep 8, 2017 at 16:13
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.