.Net Web API 002 Program和WeatherForecastController

发布时间 2023-07-31 10:23:14作者: mytudousi

创建工程后,工程主要包含了Program.cs和WeatherForecastController.cs两个代码文件,还有一个WeatherForecast.cs文件,该文件定义的天气情况数据结构替,WeatherForecastController用来组织和返回数据。

1、Program.cs文件

我们先看下Program.cs中的代码。

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();

在上面的代码中,显示创建了WebApplicationBuilder类型的builder,然后注册所有的控制器类,注册Swagger。

接下来创建App,当处于开发模式下的时候,开启Swagger。

UseHttpsRedirection为我们的应用添加了重定向HTTP请求到HTTPS请求的中间件。如果不想重定向,注释掉该代码即可。

app.UseAuthorization(),启用身份验证。

app.MapControllers(),看函数注释的意思是,将控制器动作的端点添加到Microsoft.AspNetCore.Routing.IEndpointRouteBuilder中,而不指定任何路由。感觉应该是把我们定义在各Controller里面的api函数注册一下。

app.Run(),启动Web服务。

2、WeatherForecastController.cs文件

using Microsoft.AspNetCore.Mvc;

namespace WOBM.Learn.WebAPI.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 = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}

我们先不管logger部分,除了logger部分外,该文件定义了一个类,该类继承了ControllerBase。定义了一个私有属性以及一个Get函数。

该类集成了ControllerBase,我们写WebApi类的时候,都会继承该基类。类名以Controller结尾,但不一定非得如此。但我们尽量还是按照这种方式来命名。

在类名上面,添加了两个属性标签,[ApiController]和 [Route("[controller]")]。[ApiController]表示这是一个Controller,[Route("[controller]")]是路由,[controller]表示会在访问的地址的基础上加上这个关键字来找对应的类。

例如http://localhost:5279/WeatherForecast,会访问WeatherForecastcontroller类。

函数Get函数,返回天气信息列表。函数上添加了[HttpGet(Name = "GetWeatherForecast")]依赖属性。HttpGet表示该Api是一个Get操作,Name = "GetWeatherForecast")表示调用时候的名称。