如何解决.NET Core中的中间件问题

时间:2019-08-01 19:09:35

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

在中间件中,我遇到了一些问题。我提供了通过配置文件的正确API密钥,但在allow-methods类中出现错误。我正在获取value = null。

enter image description here

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 enter image description here

它在调试点未经授权。 enter image description here

这也是邮递员的屏幕截图。

enter image description here

2 个答案:

答案 0 :(得分:1)

您需要通过使用DI在自定义中间件中使用IConfiguration来获取配置设置。

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"
      }
    }
  }
}
}

答案 1 :(得分:0)

此问题已解决。我忘了在项目内部添加app.json文件。