读取 asp.netcore 中的 appsettings.json 个值

Reading appsettings.json values in asp.netcore

我正在尝试从我的 appsettings.json 文件中读取一些值以进行基本身份验证。在本地代码工作正常,但我对如何在实时部署我的应用程序时如何做感到困惑。 我的 appsettings.json 文件看起来像这样

appsettings.json

{
  "BasicAuth": {
    "UserName": "admin",
    "Password": "1234567789"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
}

我用于中间件的代码如下所示

startup.cs

public void ConfigureServices(IServiceCollection 
{
            services.AddHttpClient("MyClient", client => {
                client.BaseAddress = new Uri("http://xx.xx.xx.xxx/1/#/nutch/query");
                client.DefaultRequestHeaders.Add("username", "admin");
                client.DefaultRequestHeaders.Add("password", "1234567789");
            });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
         app.UseMiddleware<BasicAuthMiddleware>("http://xx.xx.xx.xxx/abc/#/1/query/");
}

我的中间件 Class 看起来像这样

BasicAuthMiddleware.cs 如您所见,我必须将整个路径发送到 .AddJsonFile

中的 appsettings.json 文件
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace searchEngineTesting.Controllers
{
    public class BasicAuthMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly string _realm;

        public BasicAuthMiddleware(RequestDelegate next, string realm)
        {
            _next = next;
            _realm = realm;
        }

        public async Task Invoke(HttpContext context)
        {
            string authHeader = context.Request.Headers["Authorization"];
            if (authHeader != null && authHeader.StartsWith("Basic "))
            {
                // Get the encoded username and password
                var encodedUsernamePassword = authHeader.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries)[1]?.Trim();
                // Decode from Base64 to string
                var decodedUsernamePassword = Encoding.UTF8.GetString(Convert.FromBase64String(encodedUsernamePassword));
                // Split username and password
                var username = decodedUsernamePassword.Split(':', 2)[0];
                var password = decodedUsernamePassword.Split(':', 2)[1];
                // Check if login is correct
                if (IsAuthorized(username, password))
                {
                    await _next.Invoke(context);
                    return;
                }
            }
            // Return authentication type (causes browser to show login dialog)
            context.Response.Headers["WWW-Authenticate"] = "Basic";
            // Add realm if it is not null
            if (!string.IsNullOrWhiteSpace(_realm))
            {
                context.Response.Headers["WWW-Authenticate"] += $" realm=\"{_realm}\"";
            }
            // Return unauthorized
            context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
        }

        // Make your own implementation of this
        public bool IsAuthorized(string username, string password)
        {
            //IConfiguration config = new ConfigurationBuilder()
            //    .AddJsonFile("appsettings.json", true, true)
            //    .Build();

            IConfiguration config = new ConfigurationBuilder()
                .AddJsonFile("C:/programfiles/path/to/appsettings.json")
                .Build();
            var basicAuthUserName = config["BasicAuth:UserName"];
            var basicAuthPassword = config["BasicAuth:Password"];
            // Check that username and password are correct
            return username.Equals(basicAuthUserName, StringComparison.InvariantCultureIgnoreCase)
                   && password.Equals(basicAuthPassword);
        }
    }
}


我试过只给名字appsettings.json而不是给整个路径,但是不行,出现找不到appsettings.json文件的异常。我怎样才能给它一个通用路径,这样我就不必一次又一次地改变它,我可以读取这些值。

您可以在中间件构造函数中注入 IConfiguration。无需使用配置生成器。

private readonly RequestDelegate _next;
private readonly string _realm;
private readonly IConfiguration _configuration;

public BasicAuthMiddleware(RequestDelegate next, string realm, IConfiguration configuration)
{
    _next = next;
    _realm = realm;
    _configuration = configuration;
}