我有一个基于ASP.NET Core Web API模板的小型沙箱应用程序,其中我try 修改要基于自定义头使用的控制器/操作,为了便于实现,我替换了context.Request.Path
属性值.
然而,尽管通过调试确认中间件正在运行,替换条件正在满足,并且值Request.Path
已被更改,但应用程序仍在使用控制器和如果路径保持不变将使用的操作.
应用程序的配置为:
using Sandbox.Middleware;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseMiddleware<ModifyControllerMiddleware>();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
以及中间件本身:
namespace Sandbox.Middleware
{
public class ModifyControllerMiddleware
{
private readonly RequestDelegate _next;
public ModifyControllerMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
switch (context.Request.Headers["x-intercept"])
{
case "1":
context.Request.Path = "/Diagnostics/Heartbeat";
break;
case "2":
context.Request.Path = "/Diagnostics/Deadbeat";
break;
}
await _next(context);
}
}
}
我到底做错了什么?
总结一下我的期望:
- With no custom header
- 用户呼叫URI
https://myapplication.com/Diagnostics/Heartbeat
- 应用程序将请求发送到
Diagnostics
控制器的Heartbeat
动作
- 用户呼叫URI
- With the custom header having a value of "2"
- 用户呼叫URI
https://myapplication.com/Diagnostics/Heartbeat
- 应用程序将请求发送到
Diagnostics
控制器的Deadbeat
动作
- 用户呼叫URI
然而,实际的行为是,当调用上述URI时,无论自定义头是否存在或值如何,调用的始终是Heartbeat
操作,即使我可以看到context.Request.Path
has的值已更改.