How to create a CRUD Web API using ASP.NET Core.
SolutionIn an empty project, update the Startup class to add services and middleware for MVC.
- public void ConfigureServices(
- IServiceCollection services)
- {
- services.AddSingleton<IMovieService, MovieService>();
- services.AddMvc();
- }
- public void Configure(
- IApplicationBuilder app,
- IHostingEnvironment env)
- {
- app.UseExceptionHandler(configure =>
- {
- configure.Run(async context =>
- {
- var ex = context.Features
- .Get<IExceptionHandlerFeature>()
- .Error;
- context.Response.StatusCode = 500;
- await context.Response.WriteAsync($"{ex.Message}");
- });
- });
- app.UseMvcWithDefaultRoute();
- }
Add a service and domain model.
- public class Movie
- {
- public int Id { get; set; }
- public string Title { get; set; }
- public int ReleaseYear { get; set; }
- public string Summary { get; set; }
- }
- public interface IMovieService
- {
- List<Movie> GetMovies();
- Movie GetMovie(int id);
- void AddMovie(Movie item);
- void UpdateMovie(Movie item);
- void DeleteMovie(int id);
- bool MovieExists(int id);
- }
Add input and output models (to receive and send data via API).
- public class MovieInputModel
- {
- public int Id { get; set; }
- public string Title { get; set; }
- public int ReleaseYear { get; set; }
- public string Summary { get; set; }
- }
- public class MovieOutputModel
- {
- public int Id { get; set; }
- public string Title { get; set; }
- public int ReleaseYear { get; set; }
- public string Summary { get; set; }
- public DateTime LastReadAt { get; set; }
- }
Add a Controller for the API with service injected via constructor.
- [Route("movies")]
- public class MoviesController : Controller
- {
- [HttpGet]
- public IActionResult Get()
- {
- var model = service.GetMovies();
- var outputModel = ToOutputModel(model);
- return Ok(outputModel);
- }
- [HttpGet("{id}", Name = "GetMovie")]
- public IActionResult Get(int id)
- {
- var model = service.GetMovie(id);
- if (model == null)
- return NotFound();
- var outputModel = ToOutputModel(model);
- return Ok(outputModel);
- }
- [HttpPost]
- public IActionResult Create([FromBody]MovieInputModel inputModel)
- {
- if (inputModel == null)
- return BadRequest();
- var model = ToDomainModel(inputModel);
- service.AddMovie(model);
- var outputModel = ToOutputModel(model);
- return CreatedAtRoute("GetMovie",
- new { id = outputModel.Id }, outputModel);
- }
- [HttpPut("{id}")]
- public IActionResult Update(int id, [FromBody]MovieInputModel inputModel)
- {
- if (inputModel == null || id != inputModel.Id)
- return BadRequest();
- if (!service.MovieExists(id))
- return NotFound();
- var model = ToDomainModel(inputModel);
- service.UpdateMovie(model);
- return NoContent();
- }
- [HttpDelete("{id}")]
- public IActionResult Delete(int id)
- {
- if (!service.MovieExists(id))
- return NotFound();
- service.DeleteMovie(id);
- return NoContent();
- }
- }



Join the conversation! Your thoughts help the community grow.