zoukankan      html  css  js  c++  java
  • Aspnet core route rewrite

    设置默认http跳转到https

    创建一个空的MVC项目。找到Startup.cs文件中的 Configure方法。在 app.UseRouting(); 前加上两行代码即可。注:我本地项目中Http端口为:51812。如果运行过一次http://localhost:51812。将会被跳转到https://localhost:44319。第二次运行即使去掉下面新加的两句话也会跳转。因为在上次访问中使用的是301跳转。

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
    
        //301 代表永久跳转 44319 对应的https端口。我的开发环境为44319
        var options = new RewriteOptions().AddRedirectToHttps(301, 44319);  //新加的   
        app.UseRewriter(options);                                           //新加的
    
        app.UseRouting();
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapGet("/", async context =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        });
    }
    

      301 代表永久跳转, 44319 对应的是https端口。我的开发环境为44319。在实际生产环境中可以使用下面写法代替。

    var options = new RewriteOptions().AddRedirectToHttpsPermanent();
    app.UseRewriter(options);

      URL 重写

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
    
        /*开始*/
        var options = new RewriteOptions()
        .AddRedirect("redirect-rule/(.*)", "redirected/$1")
        .AddRewrite(@"^rewrite-rule/(d+)/(d+)", "rewritten?var1=$1&var2=$2", skipRemainingRules: true);
        app.UseRewriter(options);
        /*结束*/
    
        app.UseStaticFiles();
        app.Run(context => context.Response.WriteAsync(
            $"Rewritten or Redirected Url: " +
            $"{context.Request.Path + context.Request.QueryString}"));
    }
    

    AddRedirect中的第一个参数是正则匹配用户转进来的路径,第二个参数是替换后的路径。

    AddRewrite 中第一个参数是正则匹配用来匹配URL,第二个参数为重写后的路径,第三个参数为是否跳过剩下的规则。

  • 相关阅读:
    petshop4.0(转)
    分层依据(转)
    如何让一个函数返回多个值
    谁访问过我的电脑
    博客第一帖!
    开发辅助工具大收集
    VC 通过IHTMLINTEFACE 接口实现网页执行自定义js代码
    vi命令大全
    #include <sys/types.h>
    #include <arpa/inet.h>
  • 原文地址:https://www.cnblogs.com/lookforFree/p/14552928.html
Copyright © 2011-2022 走看看