CreatedAtRoute使用方法

[HttpGet("GetAuthorByid/{authorId}",Name =nameof(GetAuthorByid))]
        public ActionResult<AuthorDto> GetAuthorByid(Guid authorId)
        {
            var author= AuthorRepository.GetAuthor(authorId);
            if (author==null)
            {
                return NotFound();
            }
            else
            {
                return author;
            }
        }

        [HttpPost("CreateAuthor")]
        public IActionResult CreateAuthor(AuthorForCreationDto authorForCreationDto) {
            var authorDto = new AuthorDto
            {
                Name = authorForCreationDto.Name,
                Age = authorForCreationDto.Age,
                Email = authorForCreationDto.Email
            };
            AuthorRepository.AddAuthor(authorDto);

            //第一个参数是要调用Action的路由名称
            //第二个参数是包含要调用的Action的匿名对象
            //最后一个参数是添加成功后资源本身
            return CreatedAtRoute(nameof(GetAuthorByid),new { authorId=authorDto.Id}, authorDto);
        }

 添加成功后调用GetAuthorByid方法,返回码为201,在Heard头中Location中的地址为跳转的url

 

posted @ 2020-09-26 12:44  Ambition丿z  阅读(585)  评论(0)    收藏  举报