【问题标题】:Redirect ApiController based on URI string match基于 URI 字符串匹配重定向 ApiController
【发布时间】:2020-05-13 05:34:15
【问题描述】:

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

【问题讨论】:

标签: c# asp.net-mvc asp.net-core asp.net-core-webapi


【解决方案1】:

属性允许这样做。例如,假设您的控制器名为 GetAnimal

[HttpGet]
[Route("animals/{name}/{id}")]
public ActionResult GetAnimal(string name, int id)
{

    // add headers and redirect

}

【讨论】:

  • 应该是[Route("api/animals/{name}/{id}")]。加 1!
  • 正确,只要“api”部分不是类本身的默认路由,因为它往往来自 MVC 模板。
【解决方案2】:
【解决方案3】:

你可以在.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>();
        }

}

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

【讨论】:

    猜你喜欢
    • 2018-12-17
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 2018-08-18
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    相关资源
    最近更新 更多