.NET Framework 与 .NET Core 的 Web API 的模板

作者:vkvi 来源:ITPOW(原创) 日期:2022-3-31

.NET Framework 的 Web API

Visual Studio 中,建立 .NET Framework 下的 Web API 有两种方式。

首先都是选择“ASP.NET Web 应用程序(.NET Framework)”。

然后,在选择模板时,就会出现区别了。

  • 一种是直接选择“Web API”。

  • 一种是选择“空”,但勾上右边的“Web API”。

如下图是 Visual Studio 2022 的界面:

.NET Framework 下的 Web API

由于第一种方式,会强制勾上“MVC”,所以新建的项目会有很多内容,对比如下:

带 MVC 与不带 MVC 的 Web API

.NET Core 的 Web API

以 Visual Studio 2022 + .NET 6 为例,在创建“ASP.NET Core Web API”时,有一项“使用控制器”。

使用控制器

如果不勾的话,会发现少一个示例文件(WeatherForecast.cs)。

.NET Core 下的 Web API

但实际上是被移到 Program.cs 中去了。

使用控制器的 Program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();

var app = builder.Build();

// Configure the HTTP request pipeline.

app.UseAuthorization();

app.MapControllers();

app.Run();

不使用控制器的 Program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

var app = builder.Build();

// Configure the HTTP request pipeline.

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
    var forecast = Enumerable.Range(1, 5).Select(index =>
       new WeatherForecast
       (
           DateTime.Now.AddDays(index),
           Random.Shared.Next(-20, 55),
           summaries[Random.Shared.Next(summaries.Length)]
       ))
        .ToArray();
    return forecast;
});

app.Run();

internal record WeatherForecast(DateTime Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

注意

如果创建“ASP.NET Core Web 应用”,并不会像 Framework 样出来勾选“Web API”的选项,也就是说“ASP.NET Core Web 应用”与“ASP.NET Core Web API”是平级的,不像 Framework 那样属包含关系。

相关文章