根据 URI 字符串匹配重定向 ApiController

1 c# asp.net-mvc asp.net-core asp.net-core-webapi

假设我有一个像https://localhost:5000/api/animals/cat/1这样的 REST 端点,我希望重定向所有包含/animals. 在 ASP .Net Core 中是否有一种方法可以在初始阶段本身检测到调用是否包含字符串animals,然后修改该 URI 以返回添加了少量标头的不同路径?

Moh*_*and 5

您可以在 .net core 中使用中间件:

public class MyMiddleware
{
    private readonly RequestDelegate _next;
    public MyMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    public Task Invoke(HttpContext httpContext)
    {
        if (httpContext.Request.Path.ToString().Contains("animals"))
            httpContext.Response.Redirect("/animals/category-animal");

        return _next(httpContext);
    }
}
// Extension method used to add the middleware to the HTTP request pipeline.

    public static class MyMiddlewareExtensions
    {
        public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<MyMiddleware>();
        }

}
Run Code Online (Sandbox Code Playgroud)

在启动类中的 app.UseMvc() 之前添加 app.UseMyMiddleware()。