Skip to content

Instantly share code, notes, and snippets.

@223n
Last active June 17, 2018 10:09
Show Gist options
  • Save 223n/862235f05a5e5251ea9866d6a81ccb69 to your computer and use it in GitHub Desktop.
Save 223n/862235f05a5e5251ea9866d6a81ccb69 to your computer and use it in GitHub Desktop.
コントローラの作成例
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
namespace SampleProject.Controllers
{
[Route("api/[controller]")]
public class UsersController : Controller
{
// GET: api/users
[HttpGet]
public IEnumerable<Models.User> Get()
{
using (var db = new Models.Context())
if (db.Users.Any())
return db.Users.ToArray();
else
return (new List<Models.User>());
}
// GET api/users/5
[HttpGet("{id}")]
public Models.User Get(int id)
{
using (var db = new Models.Context())
return db.Users.FirstOrDefault(t => t.Id == id);
}
// POST api/users
[HttpPost]
public void Post([FromBody]Models.User value)
{
using (var db = new Models.Context())
{
value.LastUpdated = DateTime.UtcNow;
db.Add(value);
db.SaveChanges();
}
}
// PUT api/users/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]Models.User value)
{
using (var db = new Models.Context())
{
if (db.Users.Any(u => u.Id == id && u.LastUpdated == value.LastUpdated))
{
value.LastUpdated = DateTime.UtcNow;
db.Update(value);
db.SaveChanges();
}
}
}
// DELETE api/users/5
[HttpDelete("{id}")]
public void Delete(int id)
{
using (var db = new Models.Context())
if (db.Users.Any(u => u.Id == id))
{
var user = db.Users.First(u => u.Id == id);
user.LastUpdated = DateTime.UtcNow;
user.GCRecord = Guid.NewGuid().ToString();
db.Update(user);
db.SaveChanges();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment