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?

\$\endgroup\$
  • 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\$ – Jesse C. Slicer May 7 '18 at 14:38
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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.