ASP.NET Core - Azure - WinHttpException:无法解析服务器名称或地址

时间:2018-03-19 03:44:10

标签: asp.net-core startup azure-keyvault

将我的ASP.NET核心应用程序部署到Microsoft Azure(推送到临时插槽)现在开始失败,并出现以下错误:

WinHttpException: The server name or address could not be resolved
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
HttpRequestException: An error occurred while sending the request.
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
WinHttpException: The server name or address could not be resolved
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Threading.Tasks.RendezvousAwaitable.GetResult()
System.Net.Http.WinHttpHandler+<StartRequest>d__105.MoveNext()

这在启动期间发生,因此只能使用DetailedErrors和CaptureStartupErrors检测到。从较长的Stack Trace看,它看起来像是在我的AddKeyVault步骤之后发生的,当前正在生产中,但当我尝试推送更新的位或相同的代码时,我得到了这个错误。

我已尝试推送更新的位,创建新的密钥保管库并切换到该URI,尝试创建新的部署插槽以防由于某些原因它已损坏,将我的整个解决方案从ASP.NET Core 1.1更新到ASP.NET Core 2.0,都有相同的错误。

有没有人遇到这样的问题,或者有进一步调试的建议?

完整追踪:

HttpRequestException: An error occurred while sending the request.
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.ConfiguredTaskAwaitable+ConfiguredTaskAwaiter.GetResult()
System.Net.Http.HttpClient+<FinishSendAsyncBuffered>d__58.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.ConfiguredTaskAwaitable+ConfiguredTaskAwaiter.GetResult()
Microsoft.Azure.KeyVault.KeyVaultCredential+<ProcessHttpRequestAsync>d__10.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.ConfiguredTaskAwaitable+ConfiguredTaskAwaiter.GetResult()
Microsoft.Azure.KeyVault.KeyVaultClient+<GetSecretsWithHttpMessagesAsync>d__66.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.ConfiguredTaskAwaitable+ConfiguredTaskAwaiter.GetResult()
 Microsoft.Azure.KeyVault.KeyVaultClientExtensions+<GetSecretsAsync>d__49.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.Extensions.Configuration.AzureKeyVault.AzureKeyVaultConfigurationProvider+<LoadAsync>d__5.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.ConfiguredTaskAwaitable+ConfiguredTaskAwaiter.GetResult()
Microsoft.Extensions.Configuration.AzureKeyVault.AzureKeyVaultConfigurationProvider.Load()
Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList<IConfigurationProvider> providers)
Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()
Solution.Startup..ctor(IHostingEnvironment env) in Startup.cs
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    Microsoft.Extensions.Internal.ActivatorUtilities+ConstructorMatcher.CreateInstance(IServiceProvider provider)
Microsoft.Extensions.Internal.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetServiceOrCreateInstance(IServiceProvider provider, Type type)
 Microsoft.AspNetCore.Hosting.Internal.StartupLoader.LoadMethods(IServiceProvider hostingServiceProvider, Type startupType, string environmentName)
 Microsoft.AspNetCore.Hosting.WebHostBuilderExtensions+<>c__DisplayClass1_0.<UseStartup>b__1(IServiceProvider sp)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, ServiceProvider provider)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor.VisitCallSite(IServiceCallSite callSite, TArgument argument)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitSingleton(SingletonCallSite singletonCallSite, ServiceProvider provider)
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor.VisitCallSite(IServiceCallSite callSite, TArgument argument)
Microsoft.Extensions.DependencyInjection.ServiceProvider+<>c__DisplayClass22_0.<RealizeService>b__0(ServiceProvider provider)
Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService<T>(IServiceProvider provider)
Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureStartup()
Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()

我的Startup.cs

public Startup(IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();

    if (env.IsDevelopment())
    {
        builder.AddUserSecrets<Startup>();
        builder.AddApplicationInsightsSettings(developerMode: true);
    }
    else
    {
        builder.AddApplicationInsightsSettings();
    }

    var config = builder.Build();

    if (!env.IsDevelopment())
    {
        builder.AddAzureKeyVault(
            config["AzureAd:BaseKeyVaultUri"],
            config["AzureAd:ClientId"],
            config["AzureAd:GraphClientSecret"]);
    }

    this.Configuration = builder.Build();
    this.CurrentEnvironment = env;
}

/// <summary>
/// Gets the Configuration for Startup
/// </summary>
public IConfigurationRoot Configuration { get; }

/// <summary>
/// Gets or sets the Current Hosting Environment
/// </summary>
private IHostingEnvironment CurrentEnvironment { get; set; }

/// <summary>
/// This method gets called by the runtime. Use this method to add services to the container.
/// </summary>
/// <param name="services">Services to inject into or configure</param>
public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<IConfiguration>(this.Configuration);

    services.Configure<MvcOptions>(options =>
    {
        options.Filters.Add(new RequireHttpsAttribute());

        var policy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .Build();

        options.Filters.Add(new AuthorizeFilter(policy));
    });

    services.AddMvc();

    services
        .AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(options =>
        {
            options.Audience = this.Configuration["AzureAd:ClientId"];
            options.Authority = string.Format(this.Configuration["AzureAd:AadInstance"], this.Configuration["AzureAd:Tenant"]);
        })
        .AddAzureAd(options =>
        {
            options.ClientId = this.Configuration["AzureAd:ClientId"];
            options.AadInstance = this.Configuration["AzureAd:AadInstance"];
            options.Tenant = this.Configuration["AzureAd:Tenant"];
            options.GraphClientSecret = this.Configuration["AzureAd:GraphClientSecret"];
            options.GraphResourceUri = this.Configuration["AzureAd:GraphResourceUri"];
        })
        .AddCookie(options =>
        {
            options.Cookie.HttpOnly = true;
            options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
            options.ExpireTimeSpan = TimeSpan.FromMinutes(30);
        });

    services.AddAuthorization(options =>
    {
        if (this.CurrentEnvironment.IsDevelopment())
        {
            options.AddPolicy(RoleConstants.ApprovalsPolicyName, policy => policy.RequireAssertion(e => true));
            options.AddPolicy(RoleConstants.AdminPolicyName, policy => policy.RequireAssertion(e => true));
            options.AddPolicy(RoleConstants.LTPolicyName, policy => policy.RequireAssertion(e => true));
        }
        else
        {
            options.AddPolicy(RoleConstants.ApprovalsPolicyName, policy => policy.RequireRole(RoleConstants.ApprovalsRoleName));
            options.AddPolicy(RoleConstants.AdminPolicyName, policy => policy.RequireRole(RoleConstants.AdminRoleName));
            options.AddPolicy(RoleConstants.LTPolicyName, policy => policy.RequireRole(RoleConstants.LTRoleName));
        }

        // This policy ensures that applicable calls only come from the worker application.
        options.AddPolicy(
            RoleConstants.EmailRenderPolicyName,
            policy => policy.RequireClaim("appid", services.BuildServiceProvider().GetRequiredService<IConfiguration>().GetSection("Worker").GetValue<string>("ClientID")));
    });

    services.AddSession(o =>
    {
        o.Cookie.HttpOnly = true;
        o.Cookie.SecurePolicy = CookieSecurePolicy.Always;
    });

    services.AddOptions();

    services.Configure<AzureAdConfiguration>(this.Configuration.GetChildren().First(c => c.Key.Equals("AzureAd")));
    services.Configure<NominationValidationOptions>(this.Configuration.GetChildren().First(c => c.Key.Equals("NominationValidationOptions")));
    services.Configure<EmailConfig>(this.Configuration.GetChildren().First(c => c.Key.Equals("Email")));
    services.Configure<FeatureConfig>(this.Configuration.GetSection("Features"));
    services.Configure<QueueConfiguration>(this.Configuration.GetSection("Queue"));
    services.Configure<NominationConfiguration>(this.Configuration.GetSection("Nomination"));

    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    services.AddSingleton<IHostingEnvironment>(this.CurrentEnvironment);
    services.AddTransient<IValidationService, NominationValidationService>();
    services.AddTransient<IEmailService, EmailService>();
    services.AddTransient<PraiseValidationService>();

    services.AddTransient<AuthenticationHelper>();
    services.AddTransient(sp =>
        new TokenAuthenticationHttpMessageHandler(
            new HttpClientHandler(),
            sp.GetRequiredService<AuthenticationHelper>(),
            this.Configuration["AzureAd:GraphResourceUri"]));
    services.AddTransient<IMicrosoftGraphHttpClient, MicrosoftGraphHttpClient>(sp =>
        new MicrosoftGraphHttpClient(
            new Uri(this.Configuration["AzureAd:GraphResourceUri"]),
            sp.GetRequiredService<TokenAuthenticationHttpMessageHandler>(),
            true));
    services.AddTransient<IMicrosoftGraphRepository, MicrosoftGraphRepository>();
    services.AddTransient<IActiveDirectoryService, MicrosoftGraphService>();

    services.AddTransient<INominationService, NominationService>();
    services.AddTransient<INominationRepository>(_ => new NominationSqlRepository(_.GetService<SqlDatabase>()));
    services.AddTransient<INominationNoteRepository>(_ => new NominationNoteSqlRepository(_.GetService<SqlDatabase>()));
    services.AddTransient<IPraiseService, PraiseService>();
    services.AddTransient<IPraiseRepository>(_ => new PraiseSqlRepository(_.GetService<SqlDatabase>()));
    services.AddTransient<IRockstarService, RockstarService>();
    services.AddTransient<IRockstarRepository>(_ => new RockstarSqlRepository(_.GetService<SqlDatabase>()));

    services.AddTransient<IApprovalService, ApprovalService>();
    services.AddTransient<IApprovalRepository>(_ => new ApprovalSqlRepository(_.GetService<SqlDatabase>()));
    services.AddTransient<ILTService, LTService>();
    services.AddTransient<ILTApprovalRepository>(_ => new LTApprovalSqlRepository(_.GetService<SqlDatabase>()));
    services.AddTransient<ISiteContentService, SiteContentService>();
    services.AddTransient<ISiteContentRepository>((_) =>
    {
        var connectionString = this.Configuration["DefaultConnection"];
        return new SiteContentRepository(connectionString);
    });
    services.AddTransient<ITemplateService, RazorTemplateService>();
    services.AddTransient<ITemplateRepository>(_ => new TemplateFileRepository(@"Views\Template"));

    services.AddSingleton(sp => CloudStorageAccount.Parse(sp.GetRequiredService<IConfiguration>().GetSection("Queue").GetValue<string>("StorageConnectionString")));
    services.AddSingleton(sp =>
    {
        var account = sp.GetRequiredService<CloudStorageAccount>();
        return account.CreateCloudQueueClient();
    });
    services.AddTransient<IEmailQueueWriterService, EmailQueueWriterService>(sp =>
    {
        var client = sp.GetRequiredService<CloudQueueClient>();
        var queueName = sp.GetRequiredService<IOptions<QueueConfiguration>>().Value.EmailQueueName;
        var feedbackQueueName = sp.GetRequiredService<IOptions<QueueConfiguration>>().Value.FeedbackQueueName;

        var service = new EmailQueueWriterService(
            client.GetQueueReference(queueName),
            client.GetQueueReference(feedbackQueueName));
        return service;
    });
}

/// <summary>
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
/// </summary>
/// <param name="app">Application Builder</param>
/// <param name="env">Hosting Environment</param>
/// <param name="loggerFactory">Logging Factory</param>
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(this.Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Error");
    }

    app.UseWhen(context => !context.Request.IsAjaxRequest(), appBuilder =>
    {
        appBuilder.UseStatusCodePagesWithRedirects("~/Error/{0}");
    });

    app.UseSecurityHeadersMiddleware();

    app.UseStaticFiles();

    app.UseSession();

    app.UseAuthentication();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });

    var initalizer = new PropertyTelemetryInitializer(app.ApplicationServices.GetService<IHttpContextAccessor>());
    var configuration = app.ApplicationServices.GetService<TelemetryConfiguration>();
    configuration.TelemetryInitializers.Add(initalizer);
}

1 个答案:

答案 0 :(得分:0)

最后,我创建了一个新的AAD应用程序,并将其添加到Key Vault,这很有效。旧的AAD应用程序肯定存在问题,因为我所做的只是更改了ClientID,它现在正在运行。我将进一步调查此事。感谢Muneeb的帮助。