When using the "Add Scaffold" to create a new "API Controller with actions, using Entity Framework" on as ASP .NET Core 1.1 Web API, it generates the following:
// GET: api/Users
[HttpGet]
public IEnumerable<User> GetUsers()
{
try
{
return _context.Users;
}
catch (Exception ex)
{
_logger.LogError(LoggingEvents.GENERAL_EXCEPTION, ex, ex.Message);
}
}
// GET: api/Users/5
[HttpGet("{id}")]
public async Task<IActionResult> GetUser([FromRoute] int? id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var user = await _context.Users.SingleOrDefaultAsync(m => m.UserId == id);
if (user == null)
{
return NotFound();
}
return Ok(user);
}
// PUT: api/Users/5
[HttpPut("{id}")]
public async Task<IActionResult> PutUser([FromRoute] int? id, [FromBody] User user)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != user.UserId)
{
return BadRequest();
}
_context.Entry(user).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!UserExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/Users
[HttpPost]
public async Task<IActionResult> PostUser([FromBody] User user)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
_context.Users.Add(user);
await _context.SaveChangesAsync();
return CreatedAtAction("GetUser", new { id = user.UserId }, user);
}
// DELETE: api/Users/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteUser([FromRoute] int? id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var user = await _context.Users.SingleOrDefaultAsync(m => m.UserId == id);
if (user == null)
{
return NotFound();
}
_context.Users.Remove(user);
await _context.SaveChangesAsync();
return Ok(user);
}
private bool UserExists(int? id)
{
return _context.Users.Any(e => e.UserId == id);
}The first thing that popped to me when I looked at the code that Visual Studio generated, is that all the methods return a Task, and all are async, with the exception of the first one: public IEnumerable GetUsers()
Is there any reason for this? I mean, what if there is an error? It should be able to return an 500 Internal Server Error, instead of a null? And why isn't this running asynchronously?
Thanks