Async task post method WebAPI controller
$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?
c# async-await asp.net-web-api
$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.
add a comment |
$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?
c# async-await asp.net-web-api
$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 ofif (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$
– Jesse C. Slicer
May 7 '18 at 14:38
add a comment |
$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?
c# async-await asp.net-web-api
$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
c# async-await asp.net-web-api
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 ofif (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$
– Jesse C. Slicer
May 7 '18 at 14:38
add a comment |
1
$begingroup$
I'm not sure what the purpose ofif (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$
– 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
add a comment |
1 Answer
1
active
oldest
votes
$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$
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
$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$
add a comment |
$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$
add a comment |
$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$
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.
edited Jan 2 at 4:56
Jesse C. Slicer
11.4k2740
11.4k2740
answered Sep 8 '17 at 16:13
DigguDgDigguDg
235
235
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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. Similarlycon.CloseAsync()
shouldn't be necessary as exiting theusing
block should dispose (by closing) the database connection.$endgroup$
– Jesse C. Slicer
May 7 '18 at 14:38