Async task post method WebAPI controller











up vote
0
down vote

favorite












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
















bumped to the homepage by Community 9 mins ago


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















  • 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.
    – Jesse C. Slicer
    May 7 at 14:38















up vote
0
down vote

favorite












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
















bumped to the homepage by Community 9 mins ago


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















  • 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.
    – Jesse C. Slicer
    May 7 at 14:38













up vote
0
down vote

favorite









up vote
0
down vote

favorite











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















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.2k11115226




30.2k11115226










asked Sep 2 '17 at 21:01









user148014

11




11





bumped to the homepage by Community 9 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 9 mins ago


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














  • 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.
    – Jesse C. Slicer
    May 7 at 14:38


















  • 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.
    – Jesse C. Slicer
    May 7 at 14:38
















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.
– Jesse C. Slicer
May 7 at 14:38




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.
– Jesse C. Slicer
May 7 at 14:38










1 Answer
1






active

oldest

votes

















up vote
0
down vote













You Need to take care Single responsibility principal here.
Your Post method should handle only HTTP request and then it pass to other handler for further operation and after receiving result, revert back to User.



You can follow SRP and DRY principal in your code.






share|improve this answer





















    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',
    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








    up vote
    0
    down vote













    You Need to take care Single responsibility principal here.
    Your Post method should handle only HTTP request and then it pass to other handler for further operation and after receiving result, revert back to User.



    You can follow SRP and DRY principal in your code.






    share|improve this answer

























      up vote
      0
      down vote













      You Need to take care Single responsibility principal here.
      Your Post method should handle only HTTP request and then it pass to other handler for further operation and after receiving result, revert back to User.



      You can follow SRP and DRY principal in your code.






      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        You Need to take care Single responsibility principal here.
        Your Post method should handle only HTTP request and then it pass to other handler for further operation and after receiving result, revert back to User.



        You can follow SRP and DRY principal in your code.






        share|improve this answer












        You Need to take care Single responsibility principal here.
        Your Post method should handle only HTTP request and then it pass to other handler for further operation and after receiving result, revert back to User.



        You can follow SRP and DRY principal in your code.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Sep 8 '17 at 16:13









        DigguDg

        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.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


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


            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

            Create new schema in PostgreSQL using DBeaver

            Deepest pit of an array with Javascript: test on Codility

            Fotorealismo