I have this http post controller method to insert a new text message to db. Here I want to change this method to async method. I tried but still couldn’t do it. Can anyone help me? 🙂
This is my controller method
[HttpPost]
public ActionResult<Message> Create(Message message)
{
var duplicatemessage = _messageService.DuplicateMessage(message.Text);
if (duplicatemessage == null)
{
_messageService.Create(message);
return CreatedAtRoute("Api", new { id = message.Id.ToString() }, message);
}
else
{
return BadRequest(new { message = "Text Already Exist" });
}
}
These are my service class methods related to the controller post method
public Message DuplicateMessage(string Text)
{
return _messages.Find<Message>(message => message.Text == Text).FirstOrDefault();
}
public Message Create(Message message)
{
_messages.InsertOne(message);
return message;
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
try this:
public async Task<ActionResult<Message>> Create(Message message)
{
var duplicatemessage = await _messageService.DuplicateMessage(message.Text);
if (duplicatemessage == null)
{
_messageService.Create(message);
return CreatedAtRoute("Api", new { id = message.Id.ToString() }, message);
}
else
{
return BadRequest(new { message = "Text Already Exist" });
}
}
public async Task<Message> DuplicateMessage(string Text)
{
return await _messages.Set<Message>().Where(message => message.Text ==
Text).FirstOrDefaultAsync();
}
Method 2
If you want to implement the async method into your controller (i assume this is what you want). You must first make the function, DuplicateMessage or async. You can do that by making the return type a task and running it in a task.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0