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请求的路由重写,不过大家可以根据项目需要按需改造。

posted @ 2019-08-29 08:49  「圣杰」  阅读(3734)  评论(2编辑  收藏  举报