中间件之路由重写及重定向

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();
app.UseMvcWithDefaultRoute();
}
目前这个中间件还是有很多弊端,只支持get请求的路由重写,不过大家可以根据项目需要按需改造。

猜你喜欢

转载自blog.csdn.net/weixin_43214644/article/details/127972728
今日推荐