asp.net-core - 如何修复.net核心中的中间件问题
问题描述
在中间件我遇到了一些问题。我提供了正确的 API 密钥,它通过配置文件但在允许方法类中出现错误。我得到的值 = null。
public async Task Invoke(HttpContext context){
string authHeader = context.Request.Headers["Authorization"];
if (!string.IsNullOrEmpty(authHeader))
{
string[] authHeaderParams = authHeader.Split('|');
if (authHeaderParams.Length == 2)
{
string secretKey = authHeaderParams[0];
string appId = authHeaderParams[1];
HashSet<string> allowedMethods = GetAllowedMethods(secretKey, appId);
if (allowedMethods.Count > 0)
{
string[] pathSegs = context.Request.Path.Value.Split('/');
if (pathSegs.Length > 1)
{
string pendingMethod = pathSegs[1];
if (allowedMethods.Contains(pendingMethod))
{
await _next.Invoke(context);
return;
}
}
}
}
}
//Reject request if there is no authorization header or if it is not valid
context.Response.StatusCode = 401;
await context.Response.WriteAsync("Unauthorized");
这里也是邮递员的截图。
解决方案
您需要IConfiguration
在自定义中间件中使用 DI 来获取您的配置设置。
using Microsoft.Extensions.Configuration;
public class SimpleHeaderAuthorizationMiddleware
{
private readonly RequestDelegate _next;
private IConfiguration _config { get; }
public SimpleHeaderAuthorizationMiddleware(RequestDelegate next, IConfiguration config)
{
_next = next;
_config = config;
}
public async Task InvokeAsync(HttpContext context)
{
HashSet<string> allowedMethods = GetAllowedMethods("myKey", "myAppId");
// Call the next delegate/middleware in the pipeline
await _next(context);
}
private HashSet<string> GetAllowedMethods(string key, string appId)
{
HashSet<string> allowmethods = new HashSet<string>();
var settings = _config.GetSection(key: "Creds")
.GetSection(key)
.GetSection(appId)
.GetSection(key: "Methods")
.GetChildren();
foreach (IConfigurationSection m in settings )
{
allowmethods.Add(item: m.Value.ToString());
}
return allowmethods;
}
}
appSettings.json
: _
{
"Creds": {
"myKey": {
"myAppId": {
"Methods": {
"item1": "xxx",
"item2": "xxx"
}
}
}
}
}
推荐阅读
- python - Python discord self bot 不会删除直接消息中的消息
- javascript - 我应该如何创建一个将 {{trigger.message.From}} 更改为名称的函数?
- css - Blogger 中的 srcset 和特定图像大小
- bluetooth - 跨平台蓝牙开发解决方案
- javascript - 根据 GroupedList json 格式转换 Json 和组 json - React Native
- c++ - 如何在 rust cdylib 中定义 DllMain 函数?
- c - 如何使用堆栈和队列以非递归方式查找集合的所有可能子集
- javascript - 执行 UI 块时抛出异常 - 仅在手机上运行时出现错误
- c++ - 检查二维向量的元素是否为 NULL
- python - VS Code Python TensorBoard 集成不起作用