How to write a middleware as custom router in asp.net core?

穿精又带淫゛_ 提交于 2019-12-07 20:37:31

You can create an extension method to encapsulate the router configuration

public static class HelloRouterExtensions {

    public static IApplicationBuilder UseHelloRouter(this IApplicationBuilder app) {
        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);
        return app;
    }
}

Which basically turns this configuration

public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
    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);
}

into this configuration.

public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) {
    app.UseHelloRouter();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!