在 appsettings.json 中的连接字符串中转义双引号
Posted
技术标签:
【中文标题】在 appsettings.json 中的连接字符串中转义双引号【英文标题】:Escaping double quotes in connection string in appsettings.json 【发布时间】:2021-12-06 07:26:07 【问题描述】:在我的 .NET 5 Web 应用程序中,我的 appsettings.json 连接字符串如下:
"ConnectionStrings":
"Default": "Server=.; Database=XKCDPublicDb; user id=nitin;password=\"XKCDDUMMYXb\"f~\""
你可以看到密码包含双引号,所以我使用\"
转义但我仍然收到以下错误:
Format of the initialization string does not conform to specification starting at index 49.
ArgumentException: Format of the initialization string does not conform to specification starting at index 49. STACK TRACE: at Microsoft.Data.Common.DbConnectionOptions.GetKeyValuePair(String connectionString, Int32 currentPosition, StringBuilder buffer, Boolean useOdbcRules, String& keyname, String& keyvalue) at Microsoft.Data.Common.DbConnectionOptions.ParseInternal(Dictionary`2 parsetable, String connectionString, Boolean buildChain, Dictionary`2 synonyms, Boolean firstKey) at Microsoft.Data.Common.DbConnectionOptions..ctor(String connectionString, Dictionary`2 synonyms) at Microsoft.Data.SqlClient.SqlConnectionString..ctor(String connectionString) at Microsoft.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous) at Microsoft.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions) at Microsoft.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key) at Microsoft.Data.SqlClient.SqlConnection.set_ConnectionString(String value) at Microsoft.Data.SqlClient.SqlConnection..ctor(String connectionString) at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerConnection.CreateDbConnection() at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.get_DbConnection() at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected) at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.BeginTransaction(IsolationLevel isolationLevel) at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.<>c__DisplayClass22_0.<BeginTransaction>b__0(DatabaseFacade database) at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.<>c__DisplayClass12_0`2.<Execute>b__0(DbContext c, TState s) at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded) at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func`2 operation, Func`2 verifySucceeded) at Microsoft.EntityFrameworkCore.ExecutionStrategyExtensions.Execute[TState,TResult](IExecutionStrategy strategy, TState state, Func`2 operation) at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.BeginTransaction(DatabaseFacade databaseFacade, IsolationLevel isolationLevel) at Abp.EntityFrameworkCore.Uow.DbContextEfCoreTransactionStrategy.CreateDbContext[TDbContext](String connectionString, IDbContextResolver dbContextResolver) at Abp.EntityFrameworkCore.Uow.EfCoreUnitOfWork.GetOrCreateDbContext[TDbContext](Nullable`1 multiTenancySide, String name) at Abp.EntityFrameworkCore.Uow.UnitOfWorkExtensions.GetDbContext[TDbContext](IActiveUnitOfWork unitOfWork, Nullable`1 multiTenancySide, String name) at Abp.EntityFrameworkCore.Uow.UnitOfWorkDbContextProvider`1.GetDbContext(Nullable`1 multiTenancySide) at Abp.EntityFrameworkCore.Repositories.EfCoreRepositoryBase`3.GetContext() at Abp.EntityFrameworkCore.Repositories.EfCoreRepositoryBase`3.<GetQueryable>b__7_0(Type key) at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) at Abp.EntityFrameworkCore.Repositories.EfCoreRepositoryBase`3.GetQueryable() at Abp.EntityFrameworkCore.Repositories.EfCoreRepositoryBase`3.GetAllIncluding(Expression`1[] propertySelectors) at Abp.EntityFrameworkCore.Repositories.EfCoreRepositoryBase`3.GetAll() at Zikbee.Public.ZikbeeRepository.LogVisit(String ip) in C:\Users\Nitin\source\repos\ZikBee\public\src\Zikbee.Public.Application\ZikbeeRepository.cs:line 43 at Zikbee.Public.Web.Controllers.HomeController.Index() in C:\Users\Nitin\source\repos\ZikBee\public\src\Zikbee.Public.Web\Controllers\HomeController.cs:line 44 at lambda_method87(Closure , Object , Object[] ) at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync() at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextExceptionFilterAsync>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ExceptionContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeNextResourceFilter() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync() --- End of stack trace from previous location --- at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker) at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
【问题讨论】:
尝试将双引号替换为&quot;
必须使用 .Net Framework 连接字符串来转义特殊的 XML 字符。
@phuzi 这是一个 JSON 字符串,而不是 XML
这能回答你的问题吗? Escape quote in web.config connection string
【参考方案1】:
用单引号 '
将密码括起来,它起作用了
"ConnectionStrings":
"Default": "Server=.; Database=XKCDPublicDb; user id=nitin;password='XKCDDUMMYXb\"f~'"
【讨论】:
以上是关于在 appsettings.json 中的连接字符串中转义双引号的主要内容,如果未能解决你的问题,请参考以下文章
.NET Core appsettings.json 获取数据库连接字符串
需要在上下文类中进行哪些更改才能将连接字符串移动到 appsettings.json 文件中
现在可以在从 Windows 任务调度程序运行 .net 核心控制台应用程序时读取 appsettings.json 文件中存在的连接字符串
.NET Core类库项目中如何读取appsettings.json中的配置