ASP.NET CORE WEB API DEMO 02

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Demo.Models
{
    public class BookChapter
    {
        public Guid Id { get; set; }
        public int Number { get; set; }
        public string Title { get; set; }
        public int Pages { get; set; }
    }

    public interface IBookChaptersRepository
    {
        Task InitAsync();
        Task<IEnumerable<BookChapter>> GetAllAsync();
        Task<BookChapter> FindAsync(Guid id);
        Task AddAsync(BookChapter chapter);
        Task<BookChapter> RemoveAsync(Guid id);
        Task UpdateAsync(BookChapter chapter);
    }

    public class BookChaptersRepository : IBookChaptersRepository
    {
        private readonly ConcurrentDictionary<Guid, BookChapter> _chapters =
            new ConcurrentDictionary<Guid, BookChapter>();

        public async Task InitAsync()
        {
            await AddAsync(new BookChapter { Number = 1, Title = "Application Architectures", Pages = 35 });
            await AddAsync(new BookChapter { Number = 2, Title = "Core C#", Pages = 42 });
        }

        public Task<IEnumerable<BookChapter>> GetAllAsync() => 
            Task.FromResult<IEnumerable<BookChapter>>(_chapters.Values);

        public Task<BookChapter> FindAsync(Guid id)
        {
            BookChapter chapter;
            _chapters.TryGetValue(id, out chapter);
            return Task.FromResult(chapter);
        }

        public Task AddAsync(BookChapter chapter)
        {
            chapter.Id = Guid.NewGuid();
            _chapters[chapter.Id] = chapter;
            return Task.FromResult<object>(null);
        }

        public Task<BookChapter> RemoveAsync(Guid id)
        {
            BookChapter chapter;
            _chapters.TryRemove(id, out chapter);
            return Task.FromResult(chapter); ;
        }

        public Task UpdateAsync(BookChapter chapter)
        {
            _chapters[chapter.Id] = chapter;
            return Task.FromResult<object>(null);
        }
    }
}
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Demo.Models;
using Microsoft.AspNetCore.Mvc;

namespace Demo.Controllers
{
    [Produces("application/json", ("application/xml"))]
    [Route("api/[controller]")]
    public class BookChaptersController : Controller
    {
        private readonly IBookChaptersRepository _repository;
        public BookChaptersController(IBookChaptersRepository bookChaptersRepository)
        {
            _repository = bookChaptersRepository;
        }

        // GET api/bookchapters
        [HttpGet]
        public Task<IEnumerable<BookChapter>> GetBookChaptersAsync() => _repository.GetAllAsync();

        // GET api/bookchapters/guid
        [HttpGet("{id}", Name = nameof(GetBookChapterByIdAsync))]
        public async Task<IActionResult> GetBookChapterByIdAsync(Guid id)
        {
            BookChapter chapter = await _repository.FindAsync(id);
            if (chapter == null)
            {
                return NotFound();
            }
            return new ObjectResult(chapter);
        }

        // POST api/bookchapters
        [HttpPost]
        public async Task<IActionResult> PostBookChapterAsync([FromBody]BookChapter chapter)
        {
            if (chapter == null)
            {
                return BadRequest();
            }
            await _repository.AddAsync(chapter);
            return CreatedAtRoute(nameof(GetBookChapterByIdAsync), new { id = chapter.Id }, chapter);
        }

        // PUT api/bookchapters
        [HttpPut("{id}")]
        public async Task<IActionResult> PutBookChapterAsync(Guid id, [FromBody]BookChapter chapter)
        {
            if (chapter == null || id != chapter.Id)
            {
                return BadRequest();
            }
            if (await _repository.FindAsync(id) == null)
            {
                return NotFound();
            }
            await _repository.UpdateAsync(chapter);
            return new NoContentResult();
        }

        // DELETE api/bookchapters/id
        [HttpDelete("id")]
        public async Task Delete(Guid id)
        {
            await _repository.RemoveAsync(id);
        }
    }
}
using Demo.Models;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Demo
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().AddXmlSerializerFormatters();
            IBookChaptersRepository repos = new BookChaptersRepository();
            repos.InitAsync();
            services.AddSingleton(repos);
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseMvc();
        }
    }
}

相关推荐