locked
How to used _httpContextAccessor inside Startup.cs - ConfigureServices() RRS feed

  • Question

  • User-893002196 posted

    Hi,

    how can I use var path = _httpContextAccessor.HttpContext.Request.Path.Value; under ConfigureServices()?
    My code idea as below:

    public class Startup
        {       
            string clientid = "";
            string clientsecret = "";
            string aadInstance = "";
            string tenant = "";
            string connectionString = "";
            string vaultAddress = "";
            string connectionStringDev = "";
            public Startup(IConfiguration configuration)
            {
                var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables();
                clientid = configuration["AzureAd:ClientId"];
                clientsecret = configuration["AzureAd:ClientSecret"];
                aadInstance = configuration["AzureAd:Instance"];
                tenant = configuration["AzureAd:TenantId"];
                vaultAddress = configuration["KeyVaultUrl"];
                Configuration = configuration;
            }
            public async Task<string> GetAccessToken(string authority, string resource, string scope)         {             var clientId = clientid;             var clientSecret = clientsecret;             ClientCredential clientCredential = new ClientCredential(clientId, clientSecret);             var context = new AuthenticationContext(authority, TokenCache.DefaultShared);             var result = await context.AcquireTokenAsync(resource, clientCredential);             return result.AccessToken;         } 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.Configure<CookiePolicyOptions>(options =>             {                 // This lambda determines whether user consent for non-essential cookies is needed for a given request.                 options.CheckConsentNeeded = context => false;                 options.MinimumSameSitePolicy = SameSiteMode.None;             });             services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();             services.AddAuthentication(AzureADDefaults.AuthenticationScheme)                 .AddAzureAD(options => Configuration.Bind("AzureAd", options));             //Register authentication call back - this would be executed for any request to Azure key vault.               KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetAccessToken));             var path = _httpContextAccessor.HttpContext.Request.Path.Value;             var pathStr = path.Split(':')[0].ToString() + "://" + path.Split('/')[1].ToString();             var DBKeyName = (pathStr == "https://abc.azurewebsites.net") ? "DatabaseConnStr" : "DatabaseConStrDev";             var DBKeyGuid = (pathStr == "https://abc.azurewebsites.net") ? "75xx233cxxxxxxxxxxxxxxx" : "22xx06axxxxxxxxxxxxxxx";             var secret = keyVaultClient.GetSecretAsync(vaultAddress, DBKeyName, DBKeyGuid).GetAwaiter().GetResult();             var storagePrimaryAccessKey = secret.Value;             connectionString = storagePrimaryAccessKey;             services.AddDbContext<XXDBContext>(options =>     options.UseSqlServer(connectionString));

    Please advise.

    Thanks

    Regards,
    Micheale

    Wednesday, November 18, 2020 8:10 AM

Answers

  • User-474980206 posted

    No can do. A HttpContext is bound to a request. At startup there is no request.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, November 18, 2020 3:29 PM
  • User-893002196 posted

    Thanks Sir,

    I manage twist around. I added a variable into appsettings.json

    eg:    "liveSite":"true"

    Then I modify my code:- calling the variable configuration from startup. 
    If I want to upload the code to Development Site, I just need to change the variable to false.

    public class Startup
        {       
            string liveSite= "";
            :
            public Startup(IConfiguration configuration)
            {
                :
                liveSite= configuration["liveSite"];
                Configuration = configuration;
            }
    var DBKeyName = (liveSite== "true") ? "DatabaseConnStr" : "DatabaseConStrDev";
                var DBKeyGuid = (liveSite== "true") ? "75xx233cxxxxxxxxxxxxxxx" : "22xx06axxxxxxxxxxxxxxx";
                var secret = keyVaultClient.GetSecretAsync(vaultAddress, DBKeyName, DBKeyGuid).GetAwaiter().GetResult();
                var storagePrimaryAccessKey = secret.Value;
                connectionString = storagePrimaryAccessKey;

    Issue Resolved.

    Thanks.

    Regards,
    Micheale

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, November 19, 2020 12:33 AM

All replies

  • User-474980206 posted

    No can do. A HttpContext is bound to a request. At startup there is no request.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, November 18, 2020 3:29 PM
  • User-893002196 posted

    Thanks Sir,

    I manage twist around. I added a variable into appsettings.json

    eg:    "liveSite":"true"

    Then I modify my code:- calling the variable configuration from startup. 
    If I want to upload the code to Development Site, I just need to change the variable to false.

    public class Startup
        {       
            string liveSite= "";
            :
            public Startup(IConfiguration configuration)
            {
                :
                liveSite= configuration["liveSite"];
                Configuration = configuration;
            }
    var DBKeyName = (liveSite== "true") ? "DatabaseConnStr" : "DatabaseConStrDev";
                var DBKeyGuid = (liveSite== "true") ? "75xx233cxxxxxxxxxxxxxxx" : "22xx06axxxxxxxxxxxxxxx";
                var secret = keyVaultClient.GetSecretAsync(vaultAddress, DBKeyName, DBKeyGuid).GetAwaiter().GetResult();
                var storagePrimaryAccessKey = secret.Value;
                connectionString = storagePrimaryAccessKey;

    Issue Resolved.

    Thanks.

    Regards,
    Micheale

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, November 19, 2020 12:33 AM