ASP.NET CORE WEB API DEMO 02

Posted xiaowangzhi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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();
        }
    }
}

 

以上是关于ASP.NET CORE WEB API DEMO 02的主要内容,如果未能解决你的问题,请参考以下文章

将文件从 ASP.NET Core Web api 发布到另一个 ASP.NET Core Web api

ASP.NET Core Web Api 自动帮助页面

ASP.NET Core Web API

初试ASP.NET Web API/MVC API(附Demo)

Asp.Net Core 1.1 消费web api

使用 ASP.NET Core MVC 创建 Web API