Search code examples
c#asp.net-coreasync-awaitstartup

Adding string to a List using await in Startup.cs


I am trying to get Active Directory userid asynchronously in startup.cs file. At the end list return null value.

  • ASP.NET Core 3.1 web application
  • Visual Studio 2019

This is the code I have

string mylanid = "";         

app.Run(async (context) =>
{
    if ((RuntimeInformation.IsOSPlatform(OSPlatform.Linux)))
    {
        ProcessStartInfo psi = new ProcessStartInfo();
        psi.FileName = "sh";
        psi.Arguments = "-c whoami";
        psi.UseShellExecute = false;
        psi.RedirectStandardOutput = true;
        psi.RedirectStandardError = true;

        Process proc = new Process
        {
            StartInfo = psi
        };

        proc.Start();

        string output = proc.StandardOutput.ReadToEnd();

        proc.WaitForExit();

        mylanid = output;                   
    }
    else
    {
        mylanid = Environment.UserName;
    }

    List<returnedId> listData = new List<returnedId>();
    returnedId retrnTbl = new returnedId();
    retrnTbl.userRole = mylanid;
    listData.Add(retrnTbl);
});

Instead of list if I use below code. It reflects the correct result but I want that string value to be stored in List.

await context.Response.WriteAsync(mylanId);

Any help appreciated.


Solution

  • I resolved it by doing below steps;

    Firs I added this line of code at the top of Startup.cs

    public List<string> listData = new List<string>();
    

    Second , in in ConfigurationServices I added this code;

    services.AddSingleton<List<string>>(listData.ToList());
    

    And Third step , I added string data to List<string> ;

      listData.Add(mylanid);
    

    And it worked . Thanks