zoukankan      html  css  js  c++  java
  • ASP.NET Core知多少(13):路由重写及重定向

    背景

    在做微信公众号的改版工作,之前的业务逻辑全塞在一个控制器中,现需要将其按厂家拆分,但要求入口不变。

    拆分很简单,定义控制器基类,添加公用虚方法并实现,各个厂家按需重载。

    但如何根据统一的入口参数路由到不同的控制器呢?

    最容易想到的方案无外乎两种:

    1. 路由重定向
    2. 路由重写

    路由重定向


    路由重写

    简易方案

    但最最简单的办法是在进入ASP.NET Core MVC路由之前,写个中间件根据参数改掉请求路径即可,路由的事情还是让MVC替你干就好。

    定义自定义中间件:

    public class CustomRewriteMiddleware
    {
        private readonly RequestDelegate _next;
    
        //Your constructor will have the dependencies needed for database access
        public CustomRewriteMiddleware(RequestDelegate next)
        {
            _next = next;
        }
    
        public async Task Invoke(HttpContext context)
        {
            var path = context.Request.Path.ToUriComponent().ToLowerInvariant();
            var thingid = context.Request.Query["thingid"].ToString();
    
            if (path.Contains("/lockweb"))
            {
                var templateController = GetControllerByThingid(thingid);
    
                context.Request.Path =  path.Replace("lockweb", templateController);
            }
    
            //Let the next middleware (MVC routing) handle the request
            //In case the path was updated, the MVC routing will see the updated path
            await _next.Invoke(context);
    
        }
    
        private string GetControllerByThingid(string thingid)
        {
            //some logic
            return "yinhua";
        }
    }
    
    

    在startup config方法注入MVC中间件之前,注入自定义的重写中间件即可。

    public void Configure(IApplicationBuilder app
    {
      //some code
      app.UseMiddleware<CustomRewriteMiddleware>();
      app.UseMvcWithDefaultRoute();
    }
    

    目前这个中间件还是有很多弊端,只支持get请求的路由重写,不过大家可以根据项目需要按需改造。

  • 相关阅读:
    hdu 4813(2013长春现场赛A题)
    NEFU 628 Garden visiting (数论)
    FZU 2020 组合 (Lucas定理)
    HDU 3304 Interesting Yang Yui Triangle (Lucas定理)
    HDU 3037 Saving Beans (数论,Lucas定理)
    UVa 1161 Objective: Berlin (最大流)
    Vijos P1951 玄武密码 (AC自动机)
    LA 4670 Dominating Patterns (AC自动机)
    HDU 2340 Obfuscation (暴力)
    HDU 5510 Bazinga (KMP)
  • 原文地址:https://www.cnblogs.com/sheng-jie/p/11427633.html
Copyright © 2011-2022 走看看