Net Core基本路由配置学习总结

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ITzhongzi/article/details/80880294

使用方式

  • 需要在ConfigureServices中增加路由服务, services.AddRouting();
  • 在Configure中定义路由具体的实现:
    • 用 new RouteHandler定义一个默认的路由处理函数
    • 再用new RouteBuilder创建一个路由构造器,他需要两个参数,1 IApplicationBuilder实例 2 IRoute 的实例,将 Configure 的app 和我们第一步创建的默认处理函数传入进去。
    • 通过 routeBuilder.MapRoute 设置默认匹配的路由,第一个 参数 是名字,第二个 参数是 默认匹配的 地址,该地址支持 1 写死的静态url 2 模板字符串 3 正则表达式
    • 这样我们就可以 处理 所有 符合 默认路由的请求了,当请求发送过来,调用默认的 处理函数去处理
    • routeBuilder.MapGet ,该方法是定义陪陪某个 url 的GET 请求。接受两个参数,第一个 需要匹配的 url 第二个 处理该请求的函数。
    • 最后 我们用var routes = routeBuilder.Build(); 调用 build方法 来构建芦浦,并返回一个IRoute路有对象
    • 将该对象 传入我们的中间件,app.UseRouter(routes); 即可实现可以匹配默认字符串,并可以处理 一个 写好的 GET 请求的路由了。
      该示例demo通过 vs2017 的 新建项目 -> .Net Core -> ASP.NET Core Web 应用程序 -> 空项目 来初始化的。

示例demo

  • Program.cs 文件
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace NETCoreLogging
{
    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .Build();
    }
}
  • Startup.cs 文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;

namespace NETCoreLogging
{
    public class Startup
    {

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRouting();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            var trackPackageRouteHandler = new RouteHandler(context =>
            {
                var routeValues = context.GetRouteData().Values;

                return context.Response.WriteAsync(
                    $"Hello! Route values: {string.Join(", ", routeValues)}");
            });

            var routeBuilder = new RouteBuilder(app, trackPackageRouteHandler);

            routeBuilder.MapRoute(
                "Track Package Route",
                "package/{operation:regex(^(track|create|detonate)$)}/{id:int}");

            routeBuilder.MapGet("hello/{name}", context =>
            {
                var name = context.GetRouteValue("name");
                // This is the route handler when HTTP GET "hello/<anything>"  matches
                // To match HTTP GET "hello/<anything>/<anything>,
                // use routeBuilder.MapGet("hello/{*name}"
                return context.Response.WriteAsync($"Hi, {name}!");
            });

            var routes = routeBuilder.Build();

            app.UseRouter(routes);
        }
    }
}
  • demo解析: 该demo可以处理 url符合 :
URI 响应
/package/create/3 Hello! Route values: [operation, create], [id, 3]
/package/track/-3/ Hello! Route values: [operation, track], [id, -3]
/package/track/ <贯穿,无任何匹配>
GET /hello/Joe Hi, Joe!
POST /hello/Joe <贯穿,仅匹配 HTTP GET>
GET /hello/Joe/Smith <贯穿,无任何匹配>

- 示例demo2(NET Core + postgresql 数据库基本使用
- 项目结构:
这里写图片描述
- 数据库结构:
这里写图片描述

  • Program.cs 文件:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace Dboperation
{
    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .Build();
    }
}
  • Startup.cs 文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Npgsql;
using Dboperation.Data;
using Dboperation.Models;

namespace Dboperation
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRouting();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {

            var trackPackageRouteHandler = new RouteHandler(context =>
            {
                var userList = new List<User>();
                var userModels = new UserModels();
                userList = userModels.QeryUser();
                return context.Response.WriteAsync(JsonConvert.SerializeObject(userList));

            });

            var routeBuilder = new RouteBuilder(app, trackPackageRouteHandler);

            routeBuilder.MapRoute(
                "Track Package Route",
                "package/{operation:regex(^(track|create|detonate)$)}/{id:int}");

            routeBuilder.MapGet("hello/{name}", context =>
            {
                var name = context.GetRouteValue("name");

                return context.Response.WriteAsync($"Hi, {name}!");
            });

            var routes = routeBuilder.Build();

            app.UseRouter(routes);
        }
    }
}
  • User.cs 文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Dboperation.Data
{
    public class User
    {

        public string Age { get; set; }
        public string Username { get; set; }
        public int Id { get; set; }
        public string Hobby { get; set; }
        public Int64 Password { get; set; }
    }
}
  • UserModels.cs 文件
using Dboperation.Data;
using Npgsql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Dboperation.Models
{
    public class UserModels
    {
        public UserModels()
        {

        }
        public List<User> QeryUser()
        {
            var userList = new List<User>();
            using (var conn = new NpgsqlConnection("Host=localhost;Port=5432;Username=postgres;Password=admin;Database=postgres"))
            {
                conn.Open();
                using (var cmd = new NpgsqlCommand())
                {
                    cmd.Connection = conn;

                    // Insert some data
                    //cmd.CommandText = "INSERT INTO person (name,gender) VALUES ('zhangsan', 'man')";
                    //cmd.ExecuteNonQuery();

                    // Retrieve all rows
                    cmd.CommandText = "SELECT * FROM test";
                    using (var reader = cmd.ExecuteReader())
                    {

                        while (reader.Read())
                        {
                            var user = new User();
                            user.Age = (string)reader["age"];
                            user.Id = (int)reader["id"];
                            user.Hobby = (string)reader["hobby"];
                            user.Username = (string)reader["username"];
                            user.Password = (Int64)reader["password"];
                            userList.Add(user);
                        }

                    }
                }
            }
            return userList;
        }
    }
}
  • demo解析: 该示例 可以处理的 请求 和 上个demo一样,不同的是增加了 数据库的部分,将数据从postgresql中取出来之后存在 一个 List<User>的列表里,作为处理默认请求的 返回数据。
  • 运行效果展示:
    这里写图片描述

补充

在Startup.cs中加入post方式的处理方法和数据插入的方法,如下:

routeBuilder.MapGet("insert/{data}", context =>
            {
                var name = context.GetRouteValue("data");

                return context.Response.WriteAsync($"GET, Hi, {name}!");
            });
            routeBuilder.MapPost("insert/{data}", context => 
            {
                var userModels = new UserModels();
                var responseStr = userModels.InsertData();

                return context.Response.WriteAsync(responseStr);
            });

同时需要在UserModels.cs 中插入插入数据库的方法:

 public string InsertData()
        {
            var rm = new Random();
            var randomNum = rm.Next(1, 1000) * 200 % rm.Next(1, 100) * rm.Next(1, 100);
            string jsonString;
            using (var conn = new NpgsqlConnection("Host=localhost;Port=5432;Username=postgres;Password=admin;Database=postgres"))
            {
                conn.Open();
                using (var cmd = new NpgsqlCommand())
                {
                    cmd.Connection = conn;
                    cmd.CommandText = "INSERT INTO test (age, username, password, hobby)  VALUES(63, 666, 555 ,'暂无' )";
                    using (var insertResult = cmd.ExecuteReader())
                    {

                        Console.WriteLine("插入成功后返回的数据" );
                    }
                }
            }
            return "ok";
        }

在数据插入成功后 返回 “ok”

  • 接口测试:
    • 用Post方式 请求 /insert/{data} 借口:
      这里写图片描述
    • 用get方式请求 /insert/{data} 借口:
      这里写图片描述

猜你喜欢

转载自blog.csdn.net/ITzhongzi/article/details/80880294
今日推荐