问题
有时,我们可能在 Web API
中包含一些具有调试功能的请求。比如我们使用的获取配置值的功能:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
endpoints.MapGet("/test2/{key:alpha}", async context =>
{
var key = context.Request.RouteValues["key"].ToString();
foreach (var provider in Configuration.Providers.Reverse())
{
if (provider.TryGet(key, out string value))
{
await context.Response.WriteAsync(provider.ToString());
await context.Response.WriteAsync("\r\n");
await context.Response.WriteAsync(value);
break;
}
}
});
|
但你绝不会想在生产环境中暴露它们。要想实现此目的,有多种方案:
- 用户权限验证
- 编译成单独 dll,不发布到生产环境
这些方案各有利弊,这里我们介绍一种使用 Middleware
实现的简单方案。
实现

从上图可以看到,请求要访问到实际路由,需要先经过 Middleware
,我们可以在最外层的 Middleware
进行检查,只有满足条件的请求才能通过,否则返回 403 错误。
Middleware
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public class DebugMiddleware : IMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
var isDebugEndpoint = context.Request.Path.Value.Contains("/test");
var debugKey = context.Request.Query["debugKey"].ToString();
var debugKeyInConfig = "123456";//来自于配置
if (isDebugEndpoint && debugKey!=debugKeyInConfig)
{
context.SetEndpoint(new Endpoint((context) =>
{
context.Response.StatusCode = StatusCodes.Status403Forbidden;
return Task.CompletedTask;
},
EndpointMetadataCollection.Empty,
"无权访问"));
}
await next(context);
}
}
|
当请求地址包含 /test
时,检查请求参数 debugKey
是否和配置的值一样,如果不一样就返回403错误。
效果如下图:

参考
https://mp.weixin.qq.com/s?__biz=MzU3MjUzNjc1Ng==&mid=2247485938&idx=1&sn=14980684edf4de541353103f98ddd91a&chksm=fcce2b29cbb9a23f80f41d148ac543767325869bd050a37984fed1b514d61fe98f9e50e0ee24&scene=178&cur_album_id=1986653731890724865#rd