Use ASP.NET Core 3.x to build RESTful API P21 to create resources.md

Use ASP.NET Core 3.x to build RESTful API P21 to create resources


Blog Park Article Id:


Based on experience, we are doing 查询, 创建, 更新, we should use different Dto类, although most of the time, they may be members of the same, but the business is changing, create different Dtobenefit classes that can quickly help us to Reconstruction of a certain business.

Next we start to write API for creating company resources

[HttpPost]
public async Task<ActionResult<CompanyDto>> CreateCompany([FromBody]CompanyAddDto company)
{
            //当请求的Body转换成CompanyAddDto失败时,company就会为null,(在.Net Core 3.x之前,
            //因为早期版本是没有ApiController这个特性的)所以我们在此处应该判断一下,
            //但是在.Net Core 3.x (添加[ApiController特性])之后,当请求的Body转换失败之后,.Net Core 3.x 会自动返回 400 状态码,所以下面的if判断可以不写.
            if (company == null)
            {
                return BadRequest();
            }

            var entity = this._mapper.Map<Company>(company);

            this._companyRepository.AddCompany(entity);

            await this._companyRepository.SaveAsync();

            //POST请求成功之后之后,我们应该返回201状态码

            var returnDto = this._mapper.Map<CompanyDto>(entity);

            //返回插入的资源
            //第一个参数:返回可找到当前资源的URI
            //第二个参数:路由的值
            //第三个参数:返回的是响应的Body
            return CreatedAtRoute(
                nameof(GetCompany),
                new{companyId = returnDto.Id},
                returnDto);
}

In the above code, CreatedAtRoutethe first parameter of the method is to return the Action method pointed to by the URI of the currently created resource, so we need to give the method a name code as follows:

 /// <summary>
 /// 获取指定公司
 /// </summary>
 /// <param name="companyId">公司id</param>
 /// <returns></returns>
 [HttpGet("{companyId}",Name =nameof(GetCompany) )]  //注意此处的Name属性
 //[Route("{companyId}")]   //使用这种方式也能表示路由,但是不常用
 public async Task<ActionResult<Company>> GetCompany(Guid companyId)

Dto对象The code for creating company resources is as follows:

 /// <summary>
 /// 创建公司的Dto对象
 /// </summary>
 public class CompanyAddDto
 {
     
     public string Name { get; set; }
     public string Introduction { get; set; }

 }

In the CompanyProfile.csclass, the mapping relationship between the mapping CompanyAddDto and the entity Comapny, the code is as follows:

/*
 * CompanyAddDto(原对象),Company(目标对象)的映射
 */
CreateMap<CompanyAddDto,Company>();

Optimize the implementation class to add the company part of the code:

public void AddCompany(Company company)
{
    if (company == null)
    {
        throw new ArgumentException(nameof(company));
    }

    company.Id = Guid.NewGuid();

    if (company.Employees !=null)
    {
        foreach (var employee in company.Employees)
        {
            employee.Id = Guid.NewGuid();
        }

    }

    this._content.Add(company);
    //this._content.Companies.AddAsync(company);
}

Call the create company resource interface:

transfer
transfer

Call result:

Call result
Call result

Handers returned:

Handers returned
Handers returned

We can see that it is already included in the returned Headers, and we can request again the currently inserted resource URI
Location Header:http://localhost:5000/api/Companies/663b20a2-dadc-4502-a99d-57a26810530b

Request current resources
Request current resources

The insertion result is deliberately passed without parameters.The 400 status code is returned by the returned result, and this automated process is [ApiController]implemented by the feature.

Call result
Call result

Guess you like

Origin www.cnblogs.com/HelloZyjS/p/12678771.html