连接/添加数据库时,将ASP.NET Core应用程序部署到Azure失败



我正在尝试使用EF Core和Identity将ASP.NET Core 3.1应用程序部署到使用Azure SQL数据库的Azure。它成功构建,但部署失败,出现以下错误:

Trackily -> C:UsersszaptsourcerepossprzengTrackilyTrackilybinReleasenetcoreapp3.1Trackily.dll
Trackily -> C:UsersszaptsourcerepossprzengTrackilyTrackilybinReleasenetcoreapp3.1Trackily.Views.dll
Trackily -> C:UsersszaptsourcerepossprzengTrackilyTrackilyobjReleasenetcoreapp3.1PubTmpOut
Generating Entity framework SQL Scripts...
Executing command: dotnet ef migrations script --idempotent --output "C:UsersszaptsourcerepossprzengTrackilyTrackilyobjReleasenetcoreapp3.1PubTmpEFSQLScriptsTrackily.Areas.Identity.Data.TrackilyContext.sql" --context Trackily.Areas.Identity.Data.TrackilyContext 
Generating Entity framework SQL Scripts completed successfully
Adding sitemanifest (sitemanifest).
Adding database (data source=tcp:trackilydbserver.database.windows.net,1433;initial catalog=Trackily_db;user id=trackilydb@trackilydbserver)
C:Program Filesdotnetsdk3.1.400SdksMicrosoft.NET.Sdk.PublishtargetsPublishTargetsMicrosoft.NET.Sdk.Publish.MSDeploy.targets(140,5): Warning : Cannot connect to the database 'Trackily_db'.  
Retrying operation 'Add' on object dbFullSql (data source=tcp:trackilydbserver.database.windows.net,1433;initial catalog=Trackily_db;user id=trackilydb@trackilydbserver). Attempt 1 of 10.
C:Program Filesdotnetsdk3.1.400SdksMicrosoft.NET.Sdk.PublishtargetsPublishTargetsMicrosoft.NET.Sdk.Publish.MSDeploy.targets(140,5): Warning : The database 'Trackily_db' could not be created.  
Retrying operation 'Add' on object dbFullSql (data source=tcp:trackilydbserver.database.windows.net,1433;initial catalog=Trackily_db;user id=trackilydb@trackilydbserver). Attempt 2 of 10.
C:Program Filesdotnetsdk3.1.400SdksMicrosoft.NET.Sdk.PublishtargetsPublishTargetsMicrosoft.NET.Sdk.Publish.MSDeploy.targets(140,5): Warning : The database 'Trackily_db' could not be created.  
...(this continues for 10 attempts)...
C:Program Filesdotnetsdk3.1.400SdksMicrosoft.NET.Sdk.PublishtargetsPublishTargetsMicrosoft.NET.Sdk.Publish.MSDeploy.targets(140,5): Error : Web deployment task failed. ((2020-08-08 6:08:21 PM) An error occurred when the request was processed on the remote computer.)
(2020-08-08 6:08:21 PM) An error occurred when the request was processed on the remote computer.
The database 'Trackily_db' could not be created.
Login failed for user 'trackilydb'.
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at Microsoft.Web.Deployment.SqlServerDatabaseProvider.AddHelper(DeploymentObject source)
Publish failed to deploy.

这是我第一次部署应用程序并使用Azure,我遵循以下说明:

https://learn.microsoft.com/en-us/aspnet/core/tutorials/publish-to-azure-webapp-using-vs?view=aspnetcore-3.1#将应用程序部署到azure

我目前认为,将我在本地使用EF Core进行的迁移应用到Azure SQL可能会出现问题。然而,有关这方面的信息让我感到困惑,似乎应该使用以下发布设置自动应用迁移:

发布设置-1

发布设置-2

到目前为止,在开发应用程序时,我只使用了带有EF Core和Identity的本地SQL数据库(我相信是SQL Server Express LocalDB(。

appsettings.json

{
"ConnectionStrings": {
"TrackilyContextConnection": "Server=(localdb)\mssqllocaldb;Database=Trackily;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}

启动.cs

public class Startup
{
private readonly IWebHostEnvironment _env;
public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
Configuration = configuration;
_env = env;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<TrackilyContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("TrackilyContextConnection")));
services.AddDefaultIdentity<TrackilyUser>(options => options.SignIn.RequireConfirmedAccount = false)
.AddEntityFrameworkStores<TrackilyContext>();
if (_env.IsDevelopment())
{
services.Configure<IdentityOptions>(options =>
{
options.Password.RequireDigit = false;
options.Password.RequireLowercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequiredLength = 3;
options.Password.RequiredUniqueChars = 0;
options.Lockout.AllowedForNewUsers = false;
});
}
else
{
services.Configure<IdentityOptions>(options =>
{
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.User.AllowedUserNameCharacters =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-.";
options.User.RequireUniqueEmail = true;
});
}
services.AddScoped<TicketService>();
services.AddScoped<UserTicketService>();
services.AddScoped<CommentService>();
services.AddScoped<ProjectService>();
services.AddScoped<UserProjectService>();
services.AddAuthorization(options =>
{
options.AddPolicy(
"TicketEditPrivileges",
policyBuilder => policyBuilder.AddRequirements(
new TicketEditPrivilegesRequirement()
));
options.AddPolicy(
"ProjectEditPrivileges",
policyBuilder => policyBuilder.AddRequirements(
new ProjectEditPrivilegesRequirement()));
options.AddPolicy(
"ProjectDetailsPrivileges",
policyBuilder => policyBuilder.AddRequirements(
new ProjectDetailsPrivilegesRequirement()));
options.AddPolicy(
"ProjectDeletePrivileges",
policyBuilder => policyBuilder.AddRequirements(
new ProjectDeletePrivilegesRequirement()));
});
services.AddScoped<IAuthorizationHandler, TicketEditPrivilegesUserIdHandler>();
services.AddScoped<IAuthorizationHandler, ProjectEditPrivilegesProjectIdHandler>();
services.AddScoped<IAuthorizationHandler, ProjectDetailsPrivilegesProjectIdHandler>();
services.AddScoped<IAuthorizationHandler, ProjectDeletePrivilegesProjectIdHandler>();
}
public static void Configure(IApplicationBuilder app, IWebHostEnvironment env, UserManager<TrackilyUser> userManager)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == 404)
{
context.Request.Path = "/Home/Error/404";
await next();
}
});
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
DbSeeder.SeedUsers(userManager);
}
}

程序.cs

public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}

我曾尝试使用Azure门户网站上提供的连接字符串更改appsettings中的连接字符串以针对Azure SQL数据库,但这并没有修复部署。或者,我认为问题可能是将应用程序连接到Azure SQL数据库,但我不确定为什么设置连接字符串不能解决这个问题。

如有任何直接帮助或为我指明正确的方向,我们将不胜感激。

我能够解决我的问题(尽管我尝试了很多事情,但我不确定哪一个具体解决了它(。

对于其他可能遇到类似问题的人,我会尝试以下步骤:

  1. 检查您是否正在使用数据库Azure页面上的连接字符串。您应该使用管理员用户名和密码,而不是数据库用户名和密码。

  2. 添加代码以在Startup.csConfigure方法中对数据库执行迁移。例如,services.BuildServiceProvider().GetService<YourDbContextName>().Database.Migrate();

  3. 从Visual Studio的SQL Server对象资源管理器中连接到Azure SQL数据库。你可以按照这里的指南https://medium.com/net-core/deploy-an-asp-net-core-app-with-ef-core-and-sql-server-to-azure-e11df41a4804

相关内容

  • 没有找到相关文章

最新更新