剑轩

.net core3.x中间件处理路由

电脑版发表于:2020/12/9 10:11


.net core中可以使用中间件处理路由,如下在Configure直接使用:

//自定义中间件来实现一个路由
app.Use(next => async context =>
{
    if (context.Request.Path == "/")
    {
        await context.Response.WriteAsync("Hello terminal middleware!");
        return;
    }
    if (context.Request.Path == "/home/about")
    {
        context.Response.ContentType = "text/html;charset=UTF-8";
        await context.Response.WriteAsync("关于我们页面!");
        return;
    }
    if (context.Request.Path == "/home/about.html")
    {
        //context.Response.Redirect("/home/Privacy");
        context.Response.ContentType = "text/html;charset=UTF-8";
        await context.Response.WriteAsync("伪静态!");
        return;
    }
    await next(context);
});

中间件也可以封装到文件中去使用:

namespace MyFirstNETCORE.Middleware
{
    public class UrlMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger _logger;
        public UrlMiddleware(RequestDelegate next, ILoggerFactory logger)
        {
            _next = next;
            _logger = logger.CreateLogger<RequestIPMyMiddleware>();
        }
        public async Task Invoke(HttpContext context)
        {
            //if (context.Request.Path == "/")
            //{
            //    await context.Response.WriteAsync("Hello terminal middleware!");
            //    return;
            //}
            if (context.Request.Path == "/home/about")
            {
                context.Response.ContentType = "text/html;charset=UTF-8";
                await context.Response.WriteAsync("关于我们页面!");
                return;
            }
            if (context.Request.Path == "/home/about.html")
            {
                //context.Response.Redirect("/home/Privacy");
                context.Response.ContentType = "text/html;charset=UTF-8";
                await context.Response.WriteAsync("伪静态!");
                return;
            }

            await _next.Invoke(context); //执行下一个中间件
        }
    }

    public static class UrlMiddlewareExtensions 
    {
        public static IApplicationBuilder UseMyUrl(this IApplicationBuilder app)
        {
            app.UseMiddleware<UrlMiddleware>();
            return app;
        }
    }
}

然后像其他中间件一样使用即可:


关于TNBLOG
TNBLOG,技术分享。技术交流:群号677373950
ICP备案 :渝ICP备18016597号-1
App store Android
精彩评论
{{item.replyName}}
{{item.content}}
{{item.time}}
{{subpj.replyName}}
@{{subpj.beReplyName}}{{subpj.content}}
{{subpj.time}}
猜你喜欢