Visual Studio 2019 Tutorial: How to Add Web API applications to ASP.NET Core

Open Project

Open the ASP.NET Core application in Visual Studio 2019.

Adding a controller API

Right-click the project, and then add a new file named Api folder. Then, right-click the folder, and select Add> New Scaffolded Item. Use Entity Framework API Controller with selection operations. Now select an existing model class, and then click Add.

vs2019-add-scaffold-api.png

View generated by the controller

Generating code comprising a new controller class. Top of the class is defined by two properties.

[Route("api/[controller]")]
[ApiController]public class GamesController : ControllerBase
  • A first specify the route for operation of the controller api / [controller], which means that if the controller named GamesController, the route of api / Games.

  • The second attribute [ApiController] validation added to some useful categories, such as to ensure that each action contains its own method [the Route] property.

public class GamesController : ControllerBase{    private readonly AppDbContext _context;    public GamesController(AppDbContext context)    {
        _context = context;
    }

The controller using the existing AppDbContext, and passed to its constructor. Each operation will use this field to the data processing application.

// GET: api/Games[HttpGet]public IEnumerable<Game> GetGame(){    return _context.Game;
}

第一种方法是使用[HttpGet]属性指定的简单GET请求。它不带任何参数,并返回数据库中所有game的列表。

// GET: api/Games/5[HttpGet("{id}")]public async Task<IActionResult> GetGame([FromRoute] int id){    if (!ModelState.IsValid)
    {        return BadRequest(ModelState);
    }    var game = await _context.Game.FindAsync(id);    if (game == null)
    {        return NotFound();
    }    return Ok(game);
}

下一个方法指定路由中的{id},它将被添加到/之后的路由中,因此完整的路由将类似于api/Games/5,如顶部的注释所示。该id输入被映射到方法上的id参数。在方法内部,如果模型无效,则返回一个BadRequest结果。下载VS 2019否则,EF将尝试查找与提供的id匹配的记录。如果找不到,将返回NotFound结果,否则将返回相应的game记录。

// PUT: api/Games/5
[HttpPut("{id}")]
public async Task<IActionResult> PutGame([FromRoute] int id, [FromBody] Game game)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    if (id != game.Id)
    {
        return BadRequest();
    }

    _context.Entry(game).State = EntityState.Modified;

    try
    {
        await _context.SaveChangesAsync();
    }
    catch (DbUpdateConcurrencyException)
    {
        if (!GameExists(id))
        {
            return NotFound();
        }
        else
        {
            throw;
        }
    }

    return NoContent();
}

接下来,使用[HttpPut]对API的请求来执行更新。新Game记录在请求的正文中提供。执行一些验证和错误检查,如果一切顺利,数据库中的记录将使用请求体中提供的值进行更新。否则,将返回适当的错误响应。

// POST: api/Games
[HttpPost]
public async Task<IActionResult> PostGame([FromBody] Game game)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    _context.Game.Add(game);
    await _context.SaveChangesAsync();

    return CreatedAtAction("GetGame", new { id = game.Id }, game);
}

一个[HttpPost]请求用于向系统添加新记录。与[HttpPut]一样,记录被添加到请求的正文中。如果有效,则EF Core将记录添加到数据库中,并且该操作将返回更新后的记录(带有数据库生成的ID)和一个指向API记录的链接。

// DELETE: api/Games/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteGame([FromRoute] int id)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    var game = await _context.Game.FindAsync(id);
    if (game == null)
    {
        return NotFound();
    }

    _context.Game.Remove(game);
    await _context.SaveChangesAsync();

    return Ok(game);
}

最后,[HttpDelete]使用带有ID 的路由来删除记录。如果请求有效,并且存在具有给定ID的记录,那么EF Core从数据库中将其删除。

添加Swagger

Swagger是一个API文档和测试工具,可以作为一组服务和中间件添加到ASP.NET Core应用程序中。要做到这一点,请先右键单击该项目,然后选择Manage NuGet Packages。单击Browse,搜索Swashbuckle.AspNetCore并安装相应的软件包。

vs2019-nuggets-swashbuckle.png

After installation, open Startup.cs and add the following to the end ConfigureServices method:

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
});

At the same time, also you need to add Swashbuckle.AspNetCore.Swagger in the top of the file.

Next, before UseMvc, add the following in the Configure method:

// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();

// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), 
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});

Now you should be able to build and run the application.

In the browser, navigate to / swagger in the address bar, you should see a list of API endpoints and application model.

vs2019-swagger-browser.png

Click on an endpoint in the Games, in attempt to execute it, to see different endpoints.


Guess you like

Origin blog.51cto.com/14452385/2451598