参照 草根专栏- ASP.NET Core + Ng6 实战:https://v.qq.com/x/page/u0765jbwc6f.html

一、POST

安全性和幂等性

  1. 安全性是指方法执行后并不会改变资源的表述
  2. 幂等性是指方法无论执行多少次都会得到同样的结果

ASP NET Core ---POST, PUT, PATCH, DELETE,Model 验证

POST添加资源:

  • 不安全, 不幂等
  • 参数 [FromBody]
  • 返回 201 Create :    CreatedAtRoute(): 它允许响应里带着Location Header,在这个Location Header里包含着一个uri,通过这个uri就可以GET到我们刚刚创建好的资源
  • HATEOAS

 (1)添加 PostAddResource.cs 类

namespace BlogDemo.Infrastructure.Resources
{
    public class PostAddResource  
    {
        public string Title { get; set; }
        public string Body { get; set; }

        public string Remark { get; set; }
    }
}

(2)添加映射

namespace BlogDemo.Api.Extensions
{
    public class MappingProfile:Profile
    {
        public MappingProfile()
        {
            CreateMap<Post, PostDTO>().ForMember(dest=>dest.Updatetime,opt=>opt.MapFrom(src=>src.LastModified));
            CreateMap<PostDTO, Post>();
            CreateMap<PostAddResource, Post>();
        }
    }
}

(3)添加post方法:

        [HttpPost(Name = "CreatePost")]
         public async Task<IActionResult> Post([FromBody] PostAddResource postAddResource)
        {
            if (postAddResource == null)
            {
                return BadRequest();
            }

         

            var newPost = _mapper.Map<PostAddResource, Post>(postAddResource);

            newPost.Author = "admin";
            newPost.LastModified = DateTime.Now;

            _postRepository.AddPost(newPost);

            if (!await _unitOfWork.SaveAsync())
            {
                throw new Exception("Save Failed!");
            }

            var resultResource = _mapper.Map<Post, PostDTO>(newPost);

            var links = CreateLinksForPost(newPost.Id);
            var linkedPostResource = resultResource.ToDynamic() as IDictionary<string, object>;
            linkedPostResource.Add("links", links);

            return CreatedAtRoute("GetPost", new { id = linkedPostResource["Id"] }, linkedPostResource);
        }
View Code

相关文章:

  • 2021-08-05
  • 2021-10-06
  • 2022-12-23
  • 2021-12-17
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-10-08
  • 2021-10-07
  • 2021-06-13
  • 2022-12-23
  • 2021-12-23
相关资源
相似解决方案