背景
在做微信公眾號的改版工作,之前的業務邏輯全塞在一個控制器中,現需要將其按廠家拆分,但要求入口不變。
拆分很簡單,定義控制器基類,添加公用虛方法並實現,各個廠家按需重載。
但如何根據統一的入口參數路由到不同的控制器呢?
最容易想到的方案無外乎兩種:
- 路由重定向
- 路由重寫
簡易方案
但最最簡單的辦法是在進入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請求的路由重寫,不過大家可以根據項目需要按需改造。