路由主要是由Routing和Endpoints两个组件协同完成的。我们可以将ASP.NET Core的应用设为一组终结点(能够通过http请求的方式访问的远程服务)的组合。
示例:
public class demo14
{
private static readonly Dictionary<string, string> Cities = new Dictionary<string, string>
{
["010"] = "北京",
["027"] = "武汉"
};
public static void Run()
{
// ASP.NET Core为常用的验证规则定义了响应的约束表达式,我们可以根据需要为某个路由参数指定一个或多个约束表达式。
// 路由模板在被解析的时候会将带有“{}”的字符识别为参数。所以需要进行转译。
const string template = @"weather/{city}/{days:int:range(1,4)}";
// 可以在路由参数中加“?”将原本必须的路由参数变为可为空。
// 此时需要将WeatherForecast中获取路由参数改为尝试获取路由参数值
//const string template = @"weather/{city?}/{days?}";
// 尝试获取路由参数值,并赋默认值
//var city = context.GetRouteData().Values.TryGetValue("city",out var v1) ? (string)v1 : "010";
// 赋默认值方式二:
//const string template = @"weather/{city=010}/{days=3}";
Host.CreateDefaultBuilder()
.ConfigureWebHostDefaults(builder => builder
// 添加路由服务
.ConfigureServices(collection => collection.AddRouting())
.Configure(app => app
// 注册路由组件
.UseRouting()
// 注册终结点组件。
// MapGet方法将路由模板和请求处理器建立映射。
// Get表示只有get请求才会被路由到终结点上。
.UseEndpoints(endpoints => endpoints.MapGet(template, WeatherForecast))))
.Build()
.Run();
}
public static async Task WeatherForecast(HttpContext context)
{
// 获取路由参数
var city = (string)context.GetRouteData().Values["city"];
city = Cities[city];
var days = int.Parse(context.GetRouteData().Values["days"].ToString() ?? string.Empty);
var report = new WeatherReport(city, days);
await RendWeatherAsync(context, report);
}
private static async Task RendWeatherAsync(HttpContext context, WeatherReport report)
{
// 拼接响应文档
context.Response.ContentType = "text/html;charset=utf-8";
await context.Response.WriteAsync("<html><head><title>天气</title></head><body>");
await context.Response.WriteAsync($"<h3>{report.City}</h3>");
foreach (var (key, value) in report.WeatherInfos)
{
await context.Response.WriteAsync($"{key:yyyy-MM-dd};");
await context.Response.WriteAsync(
$"{value.Condition}({value.LowTemperature}℃ - {value.HighTemperature}℃)<br/><br/>");
}
await context.Response.WriteAsync("</body></html>");
}
}
/// <summary>
/// 天气对象
/// </summary>
public class WeatherReport
{
private static readonly string[] Conditions = { "晴", "多云", "小雨" };
private static readonly Random Random = new Random();
public string City { get;}
public IDictionary<DateTime, WeatherInfo> WeatherInfos { get; }
public class WeatherInfo
{
public string Condition { get; set; }
public double HighTemperature { get; set; }
public double LowTemperature { get; set; }
}
public WeatherReport(s