Visual Studio 2019教程:如何將Web API添加到ASP.NET Core應用程序

打開項目

在Visual Studio 2019中打開ASP.NET Core應用程序。

添加一個API控制器

右鍵單擊該項目,然後添加一個名爲Api的新文件夾。然後,右鍵單擊此文件夾,然後選擇Add > New Scaffolded Item。使用Entity Framework選擇帶有操作的API Controller。現在選擇一個現有的模型類,然後單擊Add。

vs2019-add-scaffold-api.png

查看生成的控制器

生成的代碼包括一個新的控制器類。類定義的頂部是兩個屬性。

[Route("api/[controller]")]
[ApiController]public class GamesController : ControllerBase
  • 第一個指定這個控制器中動作的路由爲api/[controller],這表示如果控制器名爲GamesController,則路由爲api/Games。

  • 第二個屬性[ApiController]向類添加了一些有用的驗證,比如確保每個action方法都包含自己的[Route]屬性。

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

控制器使用現有的AppDbContext,並傳遞到其構造函數中。每個操作都將使用此字段來處理應用程序的數據。

// 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-nuget-swashbuckle.png

安裝後,打開Startup.cs並將以下內容添加到ConfigureServices方法的末尾:

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

同時,還需要在文件的頂部添加Swashbuckle.AspNetCore.Swagger。

接下來,在UseMvc之前,在Configure方法中添加以下內容:

// 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");
});

現在您應該能夠構建和運行應用程序了。

在瀏覽器中,導航到/swagger地址欄中的,應該看到應用程序的API端點和模型的列表。

vs2019-swagger-browser.png

點擊Games下的一個端點,嘗試執行它,查看不同端點的行爲。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章