0

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

4
  • 1
    The usual method is via the configuration system. learn.microsoft.com/en-us/aspnet/core/fundamentals/… Define a configuration type, inject the value with an IOptions<T>, use an environment variable to provide the value. Commented Aug 6, 2024 at 2:49
  • Could you please provide the details codes with us to reproduce the issue? Commented Aug 6, 2024 at 6:56
  • I have attached the complete code. I don't understand why the variables in the console.writeline are empty. Commented Aug 6, 2024 at 13:01
  • sorry after two days i realized i had the wrong variable name. i was going crazy. everything works now. thanks to all. Commented Aug 6, 2024 at 13:25

1 Answer 1

0

Use System.Environment.GetEnvironmentVariable method, ensure that you have the environment variable set on the system or on your application config.

var value = System.Environment.GetEnvironmentVariable("yourVariableName", EnvironmentVariableTarget.Machine); // Could be Process or User depending where it is

If do you have the variable at system level, ensure that it's not set only for your user and your app is running as another user on IIS

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.