zoukankan      html  css  js  c++  java
  • ASP.NET Core中怎么实现Url rewrite功能

    我们可以使用ASP.NET Core的中间件来实现Url rewrite功能,下面我们定义一个中间件ReplaceQueryStringMiddleware来替换Http请求中的Url参数即QueryString,这相当于就是要用到以前ASP.NET的Url rewrite功能。

    中间件ReplaceQueryStringMiddleware类:

    public class ReplaceQueryStringMiddleware
    {
        private readonly RequestDelegate next;
    
        public ReplaceQueryStringMiddleware(RequestDelegate next)
        {
            this.next = next;
        }
    
        public async Task Invoke(
            Microsoft.AspNetCore.Http.HttpContext context)
        {
            var request = context.Request;
            var queryString = request.QueryString.Value;
    
                
            if (!string.IsNullOrWhiteSpace(queryString))
            {
                //如果这里给context.Request.QueryString或context.Request.Path重新赋值,相当于就是Url rewrite了 
                request.QueryString = new QueryString("?demoKey=demoValue");//注意前面要加上问号,否者会报异常
                    
            }
    
            await next.Invoke(context);
        }
    }

    中间件ReplaceQueryString的扩展类ReplaceQueryStringMiddlewareExtension:

    public static class ReplaceQueryStringMiddlewareExtension
    {
        public static void UseReplaceQueryString(this IApplicationBuilder app)
        {
            app.UseMiddleware<ReplaceQueryStringMiddleware>();
        }
    }

    Startup类的Configure方法中启用ReplaceQueryString中间件

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        //启用ReplaceQueryString中间件
        app.UseReplaceQueryString();
    
        //因为我们在app.UseMvc之前调用了app.UseReplaceQueryString将URL的QueryString替换了,所以下面使用app.UseMvc后,在MVC Controller中用Request.QueryString读到的将会是替换后的"?demoKey=demoValue"
        //同样如果在app.UseReplaceQueryString中更改了context.Request.Path的值,那么在下面app.UseMvc后,MVC读到的Request.Path也是更改后新的Url值,这会导致MVC根据新的Url来调用不同的Controller和Action,实现了Url rewrite的功能
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    
    }

    效果:

    此外,如果是一些简单的Url rewrite,那么直接在Startup类的Configure方法中用ASP.NET Core自带的中间件app.UseRewriter即可。

    注意,从ASP.NET Core 3.X开始,在Startup类的Configure方法中,app.UseReplaceQueryString要放在app.UseRouting前面,这样如果在app.UseReplaceQueryString中更改了context.Request.Path的值,ASP.NET Core MVC才会根据新的Url来调用不同的Controller和Action,来实现Url rewrite的功能:

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }
        app.UseStaticFiles();
    
        app.UseReplaceQueryString();
    
        app.UseRouting();
    
        app.UseAuthorization();
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
        });
    }
  • 相关阅读:
    个人学习代码保存:例8.在存储过程中使用简单的事务处理
    个人学习代码保存:例6.多文件上传
    泛型 .net学习日记
    .net 点击刷新验证码问题
    个人学习代码保存:例11.读取Excel文件中的数据
    个人学习代码保存:例12.读取GridView文件中的数据到Excel文件
    个人学习代码保存:例5.利用标准FileUpload单文件上传
    Android视频采集
    Android视频采集+H264编码
    实时传输协议(RTP)和实时控制协议(RTCP)
  • 原文地址:https://www.cnblogs.com/OpenCoder/p/9771856.html
Copyright © 2011-2022 走看看