ASP.NET Core:路由

 路由主要是由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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值