I'm currently doing a mock voting app using ASP.NET Core 7 Web API and Blazor WebAssembly, I still do not have database for this, so what I did is I use AddSingleton for my repository, for me to test this.
Here's our model:
public class Candidate
{
public int Id { get; set; }
public string? CandidateName { get; set; }
public int VoteCount { get; set; }
}
which has this data
1 John Doe
2 Max Smith
3 Mark Spencer
Now here's my code on doing a vote.
Here's my repository code:
public void VoteCandidate(int id)
{
Candidate candidate = _candidates.FirstOrDefault(a => a.Id == id);
if (candidate != null)
{
int currVote = candidate.VoteCount;
candidate.VoteCount = currVote++;
}
}
Here's my API code
[HttpPut]
public IActionResult SubmitVote(int id)
{
_voteRepository.VoteCandidate(id);
return Ok(_voteRepository.GetCandidateById(id));
}
We tried this and it's working fine, but when we tried to vote at the same time for Max Smith, the vote only returns 1.
Is there a way to handle a simultaneously call in API? Sorry we are all beginners when it comes to this, I hope you can help us.
Thank you.