首页 > 解决方案 > 如何修复.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");

这是即时窗口,它显示 value=null 在此处输入图像描述

它在调试点未经授权。 在此处输入图像描述

这里也是邮递员的截图。

在此处输入图像描述

标签: asp.net-core.net-core

解决方案


您需要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"
      }
    }
  }
}
}

推荐阅读