在作微信公衆號的改版工做,以前的業務邏輯全塞在一個控制器中,現須要將其按廠家拆分,但要求入口不變。web
拆分很簡單,定義控制器基類,添加公用虛方法並實現,各個廠家按需重載。微信
但如何根據統一的入口參數路由到不一樣的控制器呢?app
最容易想到的方案無外乎兩種:async
但最最簡單的辦法是在進入ASP.NET Core MVC路由以前,寫個中間件根據參數改掉請求路徑便可,路由的事情仍是讓MVC替你幹就好。ui
定義自定義中間件:code
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請求的路由重寫,不過你們能夠根據項目須要按需改造。blog