I should read an environment variable that I stored at the Windows operating system level, which contains an authentication token that my middleware class uses to authenticate me with my ASP.NET Core 8 Minimal API.
With
using APITest;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
var builder = WebApplication.CreateBuilder(args);
// Estrai la variabile d'ambiente
var Token = Environment.GetEnvironmentVariable("Token", EnvironmentVariableTarget.Machine);
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var connectionString = builder.Configuration.GetConnectionString("ConWindows");
builder.Services.AddDbContext<SqlServerDb>(options => options.UseSqlServer(connectionString));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
}
//temp test
app.UseSwagger();
app.UseSwaggerUI();
app.UseDeveloperExceptionPage();
app.UseHttpsRedirection();
// Aggiungi il middleware di autenticazione basata su token
//app.UseMiddleware<TokenAuthMiddleware>();
//
Console.WriteLine("Token from Program.cs: " + Token); // Aggiungi questa riga per verificare il token
app.MapGet("/turni/abilitati", async ([FromServices] SqlServerDb db, ILogger<Program> logger) =>
{
try
{
var turni = await db.Turni.Where(t => t.TurnoAbilitato == true).ToListAsync();
return Results.Ok(turni);
}
catch (Exception ex)
{
logger.LogError(ex, "Errore durante la ricezione dell'elenco turni!");
return Results.Problem("Errore durante la ricezione dell'elenco turni!");
}
})
.WithName("ElencoTurniAttivi")
.WithOpenApi();
//metodo get che mi restituisce la variabile d'ambiente
app.MapGet("/env/", () =>
{
var value = "Token Process: " + Environment.GetEnvironmentVariable("Token",EnvironmentVariableTarget.Process);
var value2 = "Token User: " + Environment.GetEnvironmentVariable("Token", EnvironmentVariableTarget.User);
var value3 = "Token Machine: " + Environment.GetEnvironmentVariable("Token", EnvironmentVariableTarget.Machine);
return value + " - " + value2 + " - " + value3;
})
.WithName("Tet")
.WithOpenApi();
app.Run();
//crea metodo per modificare un turno
app.MapPut("/ChiamaTurno/{id}", async ([FromServices] SqlServerDb db, int id, [FromBody] Turno turnoModificato, ILogger<Program> logger) =>
{
try
{
var turno = await db.Turni.FindAsync(id);
if (turno == null)
{
return Results.NotFound();
}
turno.ProgressivoTurno +=1;
turno.Serviti +=1;
turno.RepartoVariabile = turnoModificato.RepartoVariabile;
await db.SaveChangesAsync();
return Results.Ok(turno);
}
catch (Exception ex)
{
logger.LogError(ex, "Errore durante la chiamata del turno.");
return Results.Problem("Errore durante la chiamata del turno.");
}
})
.WithName("Aggiorna")
.WithOpenApi();
app.Run();
public class SqlServerDb : DbContext
{
public SqlServerDb(DbContextOptions<SqlServerDb> options) : base(options) { }
public DbSet<Turno> Turni { get; set; }
// Aggiungi altre DbSet per altre tabelle qui.
}
public class Turno
{
//? significa che il campo può essere null per evitare errori
public int Id { get; set; }
public string? Descrizione { get; set; }
public string? LetteraTurno { get; set; }
public int? ProgressivoTurno { get; set; }
public bool TurnoAbilitato { get; set; }
public int? CodaAttuale { get; set; }
public int? Serviti { get; set; }
public string? RepartoFisso { get; set; }
public string? RepartoVariabile { get; set; }
}
I always get an empty string, how can I solve it?
I also tried with the process, user, machine targets but I notice that these only work in debug from Visual Studio, but they don't work as soon as I publish the app in IIS.
environment variables are only output with mapget method. From console.writeline variables are empty
IOptions<T>, use an environment variable to provide the value.console.writelineare empty.