終於,開始要寫第一支WebApi,哪我就直接開始今天的主題了~~~
首先,我們先來開啟我們的terimal
後開始創第一個專案,這裡我們先輸入第一行指令
dotnet new webapi -n Demo -o Demo
就可以看到出現了新的資料夾「Demo」,我們先用VS Code來看看裡面有甚麼東西
再來可以先來執行看看會有甚麼東西,如果忘記怎麼啟動的話可以回到第二天看喔
啟動後可以在DEBUG的地方看到你啟動的路徑
然後在瀏覽器輸入路徑/WeatherForecast
就可以看到第一支Api了
用來放我們偵錯專案時套用的環境設定,例如說我們偵錯的時候預設要打開哪個頁面(launchUrl)就是在這邊設定
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false, // 啟動 Windows 身分驗證
"anonymousAuthentication": true, // 啟動匿名驗證
"iisExpress": {
"applicationUrl": "http://localhost:59278", // 應用程式啟動的 URL 路徑
"sslPort": 44326 // 啟動 SSL 的連接埠
}
},
"profiles": {
"demo": {
"commandName": "Project", // 執行應用程式的模式
"dotnetRunMessages": true,
"launchBrowser": true, // 是否啟動瀏覽器
"launchUrl": "swagger", // 啟動瀏覽器後的相對 URL 位置
"applicationUrl": "https://localhost:7284;http://localhost:5032",
// 應用程式啟動的 URL 路徑
"environmentVariables": { // 設定環境變數
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
用來放組態資料,像是連線字串、Log 的紀錄層級等等就會丟在這
在.NET Core 已經將不同職責的設定區塊拆分出去給appsettings.json、.csproj 等等,並且可以繫結強型別,所以更乾淨了
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
{自訂}+Controller.cs
using Microsoft.AspNetCore.Mvc;
namespace demo.Controllers;
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
今天我只簡單的做了幾個比較重要的介紹,那我們今天就到這裡了~