当webapp与路由不匹配时Aspnet核心代理请求

问题描述 投票:0回答:1

所以,我有一个 WebAPI 可以处理一些路由,并且需要将其余路由传递给像这样的向下 REST API

前端 ---> MyWebAPI --> AnotherAPI

任何返回 404 的请求(或者不返回,我对与现有路由不匹配的所有内容感到满意)

我设法使用 MapWhen 和 aspnetcore.Proxy 中间件来做代理。但它在任何路由匹配之前执行,所以我不知道请求是否匹配。

app.MapWhen((context) =>
                    context.Response.StatusCode == 404,
                    builder =>
                    builder.RunProxy(new ProxyOptions
                    {
                        Scheme = "http",
                        Host = Configuration.GetValue<string>("APIAddress"),
                        Port = Configuration.GetValue<string>("APIPort")
                    }));

有没有办法在路由匹配后执行此操作? 另一种方法是像这样有一个包罗万象的路线:

[Route("{*url}", Order = 999)]
public IActionResult CatchAll()
{
    //do the proxying here
}

但是我必须手动管理正确代理请求的所有细微差别。

asp.net-core
1个回答
0
投票

HttpContext.GetEndpoint()
可用于确定路线是否已匹配。

参见:https://stackoverflow.com/a/59577295

确保在

app.MapWhen
和其他
app.Routing()
中间件例程之后调用
app.
。 (我在打电话之前把我的放在最后
app.Run();

哦,请确保您已添加包

Microsoft.AspNetCore.Proxy
以启用代理功能。

app.MapWhen(
    // only execute if routing middleware did not match to an endpoint
    context => context.GetEndpoint() == null,

    // setup proxy
    builder => builder.RunProxy(new ProxyOptions()
    {
        Scheme = "http",
        Host = Configuration.GetValue<string>("APIAddress"),
        Port = Configuration.GetValue<string>("APIPort")
    })
);
© www.soinside.com 2019 - 2024. All rights reserved.