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
posted @ 2021-03-01 16:10  dudu  阅读(235)  评论(1编辑  收藏  举报