Я попробовал следующий пример: https://www.danylkoweb.com/Blog/no-configurationmanager-in-aspnet-core-GC
без удачи.
Он компилируется, но мои настройки не возвращаются. Ссылка говорит, что файл JSON должен находиться в папке конфигурации.
Есть ли другой способ сделать это?
Просто пытаюсь вставить строку подключения в файл настроек как-нибудь.
{
"Settings": {
"ConnectionString": "Data Source=XXXXXXXXXXXXXXXXXXXXXXXXXX"
}
}
public class Settings
{
public string ConnectionString { get; set; }
}
public class Startup
{
private Settings _settings;
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();//.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
//services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// Added - uses IOptions<T> for your settings.
services.AddOptions();
// Added - Confirms that we have a home for our DemoSettings
services.Configure<Settings>(Configuration.GetSection("Settings"));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseMiddleware<AuthenticationMiddleware<IOptions<Settings>>>();
app.UseHttpsRedirection();
app.UseMvc();
}
}
}
И промежуточное ПО
public class AuthenticationMiddleware<TOptions>
{
private readonly RequestDelegate _next;
private Settings _settings;
/// <summary>
///
/// </summary>
/// <param name="settings"></param>
/// <param name="next"></param>
public AuthenticationMiddleware(IOptions<Settings> settings, RequestDelegate next)
{
_next = next;
_settings = settings.Value;
}
public async Task Invoke(HttpContext context)
{
string authHeader = context.Request.Headers["Authorization"];
if (authHeader != null && authHeader.StartsWith("Basic"))
{
//Extract credentials
string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
Encoding encoding = Encoding.GetEncoding("iso-8859-1");
string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));
int seperatorIndex = usernamePassword.IndexOf(':');
var username = usernamePassword.Substring(0, seperatorIndex);
var password = usernamePassword.Substring(seperatorIndex + 1);
if (username == "test" && password == "test")
{
await _next.Invoke(context);
}
else
{
context.Response.StatusCode = 401; //Unauthorized
return;
}
}
else
{
// no authorization header
context.Response.StatusCode = 401; //Unauthorized
return;
}
}
}