How can EFCore.BulkExtensions influence DbContext connection sequence? · Issue #700 · borisdj

:root {
—animation-state: paused;
}

/* user picked a theme where the «regular» scheme is dark */
:root {
—primary: #dddddd;
—secondary: #222222;
—tertiary: #0f82af;
—quaternary: #c14924;
—highlight: #a87137;
—success: #1ca551;
}

/* these styles need to live here because the SVG has a different scope */
.dots {
animation-name: loader;
animation-timing-function: ease-in-out;
animation-duration: 3s;
animation-iteration-count: infinite;
animation-play-state: var(—animation-state);
stroke: #fff;
stroke-width: 0.5px;
transform-origin: center;
opacity: 0;
r: max(1vw, 11px);
cy: 50%;
filter: saturate(2) opacity(0.85);
}

.dots:first-child {
fill: var(—quaternary);
}

.dots:nth-child(2) {
fill: var(—quaternary);
animation-delay: 0.15s;
}

.dots:nth-child(3) {
fill: var(—highlight);
animation-delay: 0.3s;
}

.dots:nth-child(4) {
fill: var(—tertiary);
animation-delay: 0.45s;
}

.dots:nth-child(5) {
fill: var(—tertiary);
animation-delay: 0.6s;
}

@keyframes loader {
0% {
opacity: 0;
transform: scale(1);
}
45% {
opacity: 1;
transform: scale(0.7);
}
65% {
opacity: 1;
transform: scale(0.7);
}
100% {
opacity: 0;
transform: scale(1);
}
}

Sys-Admin Forum

Lots of thing to check, so maybe best to get with your IT department.

Я использовал этот код для отправки запроса cUrl, он не сработал и выдал эту ошибку:

SSL certificate problem: self signed certificate in certificate chain
php curl

curl_setopt($ch, CURLOPT_URL, "https://test.example.com/v1/authenticate.json?api_key=123456");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_CAINFO,'cert.embedapp.20191004.pem');
curl_setopt($ch,CURLOPT_CAPATH,'./cert.embedapp.20191004.pem');

Попробовав все, я изменил свой запрос cUrl на:

curl_setopt($ch, CURLOPT_URL, "https://test.example.com/v1/authenticate.json?api_key=123456");
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,0);    
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);    
curl_setopt($ch, CURLOPT_SSLCERT,'cert.embedapp.20191004.pem');

Наконец-то это работает для меня 🙂

Я изучал здесь помощь по обновлению до aspnetcore 2.1.0

Моя база данных — SQLExpress 2016SP1

Я могу добавить миграцию, но когда я выдаю

update-database

в консоли диспетчера пакетов я получаю сообщение об ошибке

A connection was successfully established with the server, but then an error occurred during the login process.
(provider: SSL Provider, error: 0 — The certificate chain was issued by an authority that is not trusted.)

Строка подключения имеет вид

   Server="Server=myserver;Initial Catalog=mydatabase;Trusted_Connection=True;MultipleActiveResultSets=true

DbContext — это

public class ApiDbContext : IdentityDbContext<ApplicationUser>
{
    public ApiDbContext(DbContextOptions<ApiDbContext> options)
        : base(options)
    {
    }
}
public class MyContextFactory : IDesignTimeDbContextFactory<ApiDbContext>
{
    public ApiDbContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<ApiDbContext>();
        var builder = new ConfigurationBuilder();
        builder.AddJsonFile("appsettings.json");
        var config = builder.Build();
        var connectionString = config.GetConnectionString("MyDatabase");
        optionsBuilder.UseSqlServer(connectionString);
        return new ApiDbContext(optionsBuilder.Options);
    }
}

Если я жестко закодирую строку подключения внутри реализации IDesignTimeDbContextFactory, я могу запустить миграции

public class MyContextFactory : IDesignTimeDbContextFactory<ApiDbContext>
{
    public ApiDbContext CreateDbContext(string[] args)
    {
        var optionsBuilder = new DbContextOptionsBuilder<ApiDbContext>();
        var connectionString =    "Server=myserver;Initial Catalog=mydatabase;Trusted_Connection=True;MultipleActiveResultSets=true";
        optionsBuilder.UseSqlServer(connectionString);
        return new ApiDbContext(optionsBuilder.Options);
    }
}

Жесткое кодирование строки подключения нежелательно, поэтому я хотел бы получить лучший ответ.

Читать также:  Сертификат дополнительного образования что это и для чего и где получить барнаул

Мне неясно, зачем нужна реализация IDesignTimeDbContextFactory. (без этого моя миграция не удалась)

Я обновил свои Startup.cs и Progam.cs, чтобы они соответствовали таковым для вновь созданной программы, реализация которой не требуется.

 public class Program
 {
   public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    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 =>
        {
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddDbContext<ApiDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("MyDatabase")));
        services.AddDefaultIdentity<IdentityUser>()
            .AddEntityFrameworkStores<ApiDbContext>();

services.AddMvc (). SetCompatibilityVersion (CompatibilityVersion.Version_2_1);
}

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();

        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseCookiePolicy();
        app.UseAuthentication();
        app.UseMvc();
    }
}

Я обновился до VS2017 версии 15.7.3.
Когда я решил повторить проблему и создать первую миграцию, личный кабинет отобразил сообщение

The configuration file 'appsettings.json' was not found and is not optional

Когда я всегда отмечал эту копию файла, работали и добавление-миграция, и база данных обновления.

A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - Цепочка сертификатов выпущена центром сертификации, не имеющим доверия.)
   at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParserStateObject.ThrowExceptionAndWarning(Boolean callerHasConnectionLock, Boolean asyncClose)
   at Microsoft.Data.SqlClient.TdsParserStateObject.SNIWritePacket(PacketHandle packet, UInt32& sniError, Boolean canAccumulate, Boolean callerHasConnectionLock)
   at Microsoft.Data.SqlClient.TdsParserStateObject.WriteSni(Boolean canAccumulate)
   at Microsoft.Data.SqlClient.TdsParserStateObject.WritePacket(Byte flushMode, Boolean canAccumulate)
   at Microsoft.Data.SqlClient.TdsParser.TdsLogin(SqlLogin rec, FeatureExtension requestedFeatures, SessionData recoverySessionData, FederatedAuthenticationFeatureExtensionData fedAuthFeatureExtensionData)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.Login(ServerInfo server, TimeoutTimer timeout, String newPassword, SecureString newSecurePassword)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance)
   at Microsoft.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, Boolean applyTransientFaultHandling, String accessToken, DbConnectionPool pool)
   at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
   at Microsoft.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions)
   at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at Microsoft.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   at Microsoft.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at Microsoft.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at Microsoft.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry, SqlConnectionOverrides overrides)
   at Microsoft.Data.SqlClient.SqlConnection.Open(SqlConnectionOverrides overrides)
   at Microsoft.Data.SqlClient.SqlConnection.Open()
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerConnection.OpenDbConnection(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternal(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.InitializeReader(Enumerator enumerator)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.<>c.<MoveNext>b__19_0(DbContext _, Enumerator enumerator)
   at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
   at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
   at System.Linq.Enumerable.TryGetSingle[TSource](IEnumerable`1 source, Boolean& found)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
   at System.Linq.Queryable.Count[TSource](IQueryable`1 source)
   at Program.<Main>$(String[] args) in D:\Projects\TestBulkExtensionsError\TestBulkExtensionsError\Program.cs:line 4

I’m not sure how EFCore.BulkExtensions package is influencing but the exception happens only when it’s installed in the project.
Also, when testing the same test app with a local instance with and without EFCore.BulkExtensions everything works fine.

Читать также:  Государственный жилищный сертификат на улучшение жилищных условий условия

A connection string used for a remote server looks like this:

Server=host_name;Database=database_name;User Id=user_name;Password=password;

Any ideas how these could be related?

P.S. SQL Server 2019 Standard was installed with all the default settings on a Windows Server 2019 Standard.
I’ve never had this kind of an issue with my other projects using EFCore.BulkExtensions with this server. But they are .Net Core 2x and 3x versions (with old version of EFCore.BulkExtensions).

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *