• ASP.NET Core 路由手动挡:借助路由从 url 取值


    问题场景

    基于 ASP.NET Core 路由模板(route template)从 url 字符串取值,路由模板是 "/{blogApp}/{postType}/{idOrSlug}.html",需要取值的博文 url 地址示例 https://www.cnblogs.com/cmt/p/14408628.html

    实现代码

    参考 ASP.NET Core 源码中的测试代码 RouteTest.cs#L56,通过 Route.RouteAsync() 方法实现了,RouteTest 中好几处用了 Mock,这里实现时没有使用 Mock。

    实现代码如下

    class Program
    {
        static async Task Main(string[] args)
        {
            var requestPath = "/cmt/p/14408628.html";
    
            var routeTemplate = "/{blogApp}/{postType}/{idOrSlug}.html";
            var routeHandler = new RouteHandler((context) => null);
    
            IServiceCollection services = new ServiceCollection();
            services.AddSingleton<ILoggerFactory>(NullLoggerFactory.Instance);
            services.AddOptions<RouteOptions>();
            var sp = services.BuildServiceProvider();
            var routeOptions = sp.GetRequiredService<IOptions<RouteOptions>>();
            var inlineConstraintResolver = new DefaultInlineConstraintResolver(routeOptions, sp);
    
            var route = new Route(
                routeHandler,
                routeTemplate,
                defaults: null,
                constraints: new RouteValueDictionary(),
                dataTokens: null,
                inlineConstraintResolver: inlineConstraintResolver);
    
            var httpContext = new DefaultHttpContext();
            httpContext.Request.Path = new PathString(requestPath);
            httpContext.RequestServices = sp;
            var routeContext = new RouteContext(httpContext);
    
            await route.RouteAsync(routeContext);
    
            Console.WriteLine("blogApp: " + routeContext.RouteData.Values["blogApp"]);
            Console.WriteLine("postType: " + routeContext.RouteData.Values["postType"]);
            Console.WriteLine("idOrSlug: " + routeContext.RouteData.Values["idOrSlug"]);
        }
    }
    

    输出结果如下

    blogApp: cmt
    postType: p
    idOrSlug: 14408628
    
  • 相关阅读:
    c++ 动态生成string类型的数组
    c++ string类型的定义及方法
    c++数字和字符串的转换
    c++ 怎么输出保留2位小数的浮点数
    c++中结构体sort()排序
    O(N)时间的排序
    复杂链表的复制
    反转链表
    判断是否为平衡二叉树
    学习笔记_过滤器详细_2(过滤器JavaWeb三大组件之一)
  • 原文地址:https://www.cnblogs.com/dudu/p/14464209.html
Copyright © 2020-2023  润新知