基礎(chǔ)環(huán)境
開發(fā)框架:.net core 2.1
開發(fā)工具:vs code
測試工具:postman參考
ubuntu下安裝 dotnet
https://www.microsoft.com/net/download/linux-package-manager/ubuntu18-04/sdk-current
.net core 文檔
https://docs.microsoft.com/zh-cn/dotnet/core/tools/dotnet-new?tabs=netcore21
首先使用dotnet 提供的腳手架創(chuàng)建應(yīng)用
在主目錄下 demo 文件下叭披,右鍵【在終端打開】
輸入命令,創(chuàng)建一個名為 chapter1-webapi 的webapi類型的例子
dotnet new webapi -n chapter1-webapi
運(yùn)行程序
dotnet restore
dotnet run
控制臺輸出:
daijinming@dai-u:~/demo/chapter1-webapi$ dotnet run
Using launch settings from /home/daijinming/demo/chapter1-webapi/Properties/launchSettings.json...
info: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[0]
User profile is available. Using '/home/daijinming/.aspnet/DataProtection-Keys' as key repository; keys will not be encrypted at rest.
Hosting environment: Development
Content root path: /home/daijinming/demo/chapter1-webapi
Now listening on: https://localhost:5001
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
在 /Controllers/ValuesController.cs 中是默認(rèn)預(yù)置的API代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace chapter1_webapi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public ActionResult<string> Get(int id)
{
return "value";
}
// POST api/values
[HttpPost]
public void Post([FromBody] string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
在使用postman測試API的時候注意關(guān)閉“SSL certificate verification” 乌叶,設(shè)置方式:File->Setting->General->SSL certificate verification聚霜。因為之前運(yùn)行 dotnet run 的時候開始了 https://localhost:5001 服務(wù)炸卑,如果不忽律證書的話postman測試的時候根本獲得不來任何輸出晨雳。
POSTMAN中的代碼
GET /api/Values HTTP/1.1
Host: localhost:5000
Cache-Control: no-cache
Postman-Token: fe637e3e-5038-43f7-ab26-8e5963e961c3
輸出信息
[
"value1",
"value2"
]