Async task post method WebAPI controller












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?










share|improve this question











$endgroup$




bumped to the homepage by Community 21 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.











  • 1




    $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
















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?










share|improve this question











$endgroup$




bumped to the homepage by Community 21 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.











  • 1




    $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














0












0








0


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?










share|improve this question











$endgroup$




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?







c# async-await asp.net-web-api






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Sep 2 '17 at 21:03









Jamal

30.3k11117227




30.3k11117227










asked Sep 2 '17 at 21:01









user148014user148014

11




11





bumped to the homepage by Community 21 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







bumped to the homepage by Community 21 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.










  • 1




    $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$
    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




1




$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




$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 Answer
1






active

oldest

votes


















0












$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.






share|improve this answer











$endgroup$













    Your Answer





    StackExchange.ifUsing("editor", function () {
    return StackExchange.using("mathjaxEditing", function () {
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    });
    });
    }, "mathjax-editing");

    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "196"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f174669%2fasync-task-post-method-webapi-controller%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0












    $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.






    share|improve this answer











    $endgroup$


















      0












      $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.






      share|improve this answer











      $endgroup$
















        0












        0








        0





        $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.






        share|improve this answer











        $endgroup$



        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.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jan 2 at 4:56









        Jesse C. Slicer

        11.4k2740




        11.4k2740










        answered Sep 8 '17 at 16:13









        DigguDgDigguDg

        235




        235






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Code Review Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f174669%2fasync-task-post-method-webapi-controller%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            How to make a Squid Proxy server?

            Is this a new Fibonacci Identity?

            19世紀