【问题标题】:Determine correct connectionString for web publishing for ASP.NET-MVC application为 ASP.NET-MVC 应用程序的 Web 发布确定正确的连接字符串
【发布时间】:2014-12-03 02:50:47
【问题描述】:

在本地机器上开发 ASP.NET-MVC 应用程序期间,我使用了这个connectionString,没有任何问题:

<connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\AppDb.mdf;Initial Catalog=AppDb;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
</connectionStrings>

在托管服务数据库控制面板中,我可以获取到我的 MSSQL 的连接字符串(我选择了 SQL Server 2012 数据库,但如果有帮助,我可以选择 2014)。他们说连接字符串是:

"Data Source=SQL5013.myASP.NET;Initial Catalog=DB_9B42A0_baza;User Id=DB_9B42A0_baza_admin;Password=YOUR_DB_PASSWORD;"

关于我的 MSSQL 数据库的信息:

Server name :   SQL5013
Server version :    Microsoft SQL Server 2012 - 11.0.5058.0 (X64) 
May 14 2014 18:34:29 
Standard Edition (64-bit) on Windows NT 6.3 (Build 9600: )
Database name:DB_9B42A0_baza    
Server URL:SQL5013.myASP.NET    
Login name:DB_9B42A0_baza_admin

我的应用程序是带有实体框架 6 的 ASP.NET-MVC5.1。

这是我尝试过的:

尝试 1

&lt;connectionStrings&gt; &lt;/connectionStrings&gt;之间添加了这个连接定义

 <add name="DefaultConnection" connectionString="Data Source=SQL5013.myASP.NET;Initial Catalog=DB_9B42A0_baza;User Id=DB_9B42A0_baza_admin;Password=12345678;" providerName="System.Data.SqlClient" />

访问我的网站时的结果:

Exception Details: System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0.

尝试 2

<add name="DefaultConnection" connectionString="Provider=sqloledb;Data Source=SQL5013,1433;Initial Catalog=DB_9B42A0_baza;User Id=DB_9B42A0_baza_admin;Password=12345678;" providerName="System.Data.SqlClient" />

访问我的网站时的结果:

Exception Details: System.ArgumentException: Keyword not supported: 'provider'.

尝试 3

<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\AppDb.mdf;Initial Catalog=AppDb;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />

加上 WebApplication2(这是我的 ASP.NET-MVC 应用程序的名称)属性:

访问我的网站时的结果:

Exception Details: System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0.

尝试 4(基于 http://www.connectionstrings.com/sqlconnection/ 的第一个示例)

<add name="DefaultConnection" connectionString="Server=SQL5013.myASP.NET;Database=DB_9B42A0_baza;User Id=DB_9B42A0_baza_admin;Password=12345678;" providerName="System.Data.SqlClient" />

访问我的网站时的结果:

Exception Details: System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0.

总结:

在过去的 3 天里,我尝试了更多的方法来使其正常工作,但我不记得了。我阅读了很多 MSDN 文章,但没有运气。如果我可以提供有关数据库或应用程序的更多信息,请告诉我会尽快更新帖子。

问题:

发布后我应该在&lt;connectionStrings&gt; &lt;/connectionStrings&gt; seciton 中写什么才能使数据库连接正常工作?


其他信息:

我的完整 Web.config 文件是:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>   
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\AppDb.mdf;Initial Catalog=AppDb;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.web>
    <customErrors mode="Off"/>
  </system.web>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5.1" />
    <httpRuntime targetFramework="4.5.1" />
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthenticationModule" />
    </modules>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.1.0.0" newVersion="5.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http.Primitives" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.0.10.0" newVersion="4.0.10.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

更新 -> 数据库代码

Application_Start in Global.asax

namespace WebApplication2 {
    public class MvcApplication : System.Web.HttpApplication {
        protected void Application_Start() {
            System.Diagnostics.Debug.WriteLine("Application_Start");
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<ApplicationDbContext, Configuration>());
            new ApplicationDbContext().Database.Initialize(true);
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

还有Configuration/Migrations.cs 文件:

namespace WebApplication2.Migrations {
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.EntityFramework;
    using System;
    using System.Collections.Generic;
    using System.Data.Entity.Migrations;
    using System.Data.Entity.Validation;
    using System.Linq;
    using WebApplication2.Models;

    internal sealed class Configuration : DbMigrationsConfiguration<WebApplication2.Models.ApplicationDbContext> {
        public Configuration() {
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = true;
            ContextKey = "WebApplication2.Models.ApplicationDbContext";
        }

        protected override void Seed(WebApplication2.Models.ApplicationDbContext context) {
            System.Diagnostics.Debug.WriteLine("SEED STARTED");

        }
    }
}

Models/IdentityModels.cs 我的DbContext 定义在哪里:

using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System;
using System.Collections.Generic;

namespace WebApplication2.Models {
    // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
    public class ApplicationUser : IdentityUser {

        USER PROPERTIES HERE

        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }
    }

    public class ApplicationDbContext : IdentityDbContext<ApplicationUser> {


        public ApplicationDbContext()
            : base("DefaultConnection", throwIfV1Schema: false) {
            System.Diagnostics.Debug.WriteLine("CONSTRUCTOR");
            Configuration.LazyLoadingEnabled = true;
            Configuration.ProxyCreationEnabled = true;
        }

       DBSETS HERE

        protected override void OnModelCreating(DbModelBuilder modelBuilder) {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<Person>().HasMany(p => p.Answers).WithMany(a => a.Persons);
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        }

        public static ApplicationDbContext Create() {

            return new ApplicationDbContext();

        }


    }
}

脚注

我没有资格在提出问题后的 2 天内开始赏金,但如果这有助于我为工作连接字符串提供 500 个声望点(我将在可能的赏金时奖励它)。这对我来说太难了,我尝试了 3 天无数的东西。

【问题讨论】:

  • 连接字符串的最佳资源是connectionstrings.com
  • @DavidG 谢谢。我以前去过那里。我根据他们的语法在原始帖子中添加了Attempt 4。也许我的 Web.config 实体框架部分有问题?在本地,一切总是毫无例外地工作(使用我在原始帖子顶部发布的 LocalDb 连接字符串),永远。这是我的网站:informatyka4444-001-site1.myasp.net
  • 你能展示你用来检索和使用连接字符串的代码吗?
  • @DavidG 我想我不明白。你问我如何生成我放在 Web.config 中的连接字符串?
  • 发布项目后,通过 ftp 连接到服务器并将 web.config 文件拉下并在本地文本编辑器中打开。我很想知道该文件中的内容作为您的连接字符串。我怀疑 VS 正在运行一些发布转换,这会导致它失败。

标签: sql-server asp.net-mvc database web-config connection-string


【解决方案1】:

尝试 2 中的连接字符串不正确,如错误所述。尝试 3 中的连接字符串指向本地。但是尝试 1 和 4 看起来完全有效。

您是否尝试过使用right click on the project--&gt;Publish 而不是project properties--&gt;Package/Publish SQL 发布网站?

请注意,使用 Project properties--&gt;Package/Publish SQL 时,它不会更新目标上的 web.config,并且需要进行 web 配置转换。如果您没有使用转换,则连接字符串将指向您在本地拥有的那个。

使用right click on the project--&gt;Publish,您可以提供目标连接字符串,对其进行测试,然后甚至可以在部署期间将此更新为web.config。确保选中 Use this connection string at runtime (update destination web.config)

更新:

关于你的问题——“为什么我之前的尝试失败了?

如上,尝试 1 和 4 看起来您有一个有效的连接字符串,但仍然收到错误

System.ArgumentException: Format of the initialization string does not conform to specification starting at index 0

出现此错误的原因可能有多种——herehere 提出的类似问题有不同的解决方案。但很可能是因为连接字符串不正确。

确保的唯一方法是,在部署/发布到托管服务后检查 web.config 中的内容。如果您确定部署后的 web.config 具有与尝试 1 和 4 相同的连接字符串,那么这确实很奇怪。

另外,在尝试 3 中,Connection string for destination database 看起来与您的其他连接字符串不同,是否经过测试?这一点以及我上面提到的网络发布方法而不是使用Package/Publish SQL 的事实让我认为数据库可能没有在您之前的尝试中部署。为什么不重复相同的步骤,但将其部署到您访问 web.config 的位置并检查 db 是否部署成功?

现在,关于 -“在我的情况下,在不向“发布 Web 设置”选项卡添加任何内容的情况下,在服务器上发布 Web 应用程序后,部分或 Web.config 应该如何使数据库正常工作?

通过不在Publish Web 工具的Settings 选项卡的Database 部分中设置任何内容,您的数据库将不会被部署。考虑到您正在使用迁移,我不确定您是否愿意这样做。

但是,如果您出于某种原因计划单独部署数据库 - 那么您需要对 web.config 应用转换以使其在发布时自动更改连接字符串。

有关如何进行 web.config 转换的更多信息可以找到here

以下页面是了解网络和数据库发布的好地方

  • MSDN - 涵盖完整的部署概述,包括代码优先迁移
  • ASP.NET site - 专注于托管服务部署和不同环境的部署

希望这会有所帮助。

【讨论】:

  • 同上:“确保的唯一方法是,在部署/发布到托管服务后检查 web.config 中的内容。如果您确定部署后的 web.config 具有与尝试 1 和 4 相同的连接字符串,那么确实很奇怪。”
  • @Ted 我在我的 FTP 中得到了这个(两个连接):&lt;connectionStrings&gt; &lt;add name="DefaultConnection" connectionString="Data Source=SQL5013.myASP.NET;Initial Catalog=DB_9B42A0_baza;User ID=DB_9B42A0_baza_admin;Password=12345678;MultipleActiveResultSets=True" providerName="System.Data.SqlClient"/&gt; &lt;add name="DefaultConnection_DatabasePublish" connectionString="Data Source=SQL5013.myASP.NET;Initial Catalog=DB_9B42A0_baza;User ID=DB_9B42A0_baza_admin;Password=12345678" providerName="System.Data.SqlClient"/&gt; &lt;/connectionStrings&gt;
  • @Yoda 以上是Publish 工具生成的工作连接字符串。 DefaultConnection 由 Web 应用程序使用,DefaultConnection_DatabasePublish 在部署期间创建,用于代码优先迁移以更新数据库架构和播种。您当前使用的部署方法是完全有效的,但如果您热衷于找出第一种方法不起作用的原因,那么您将不得不重做相同的步骤并检查配置和数据库。该错误的原因可能是当时 Web 应用使用的连接字符串不正确,或者可能是未部署数据库。
  • 我犯了一个错误,我要求版主注意不要给下面的托尼+500。我很快就点击了,因为我看到了托尼……我觉得自己像个 d@ck。
  • @Yoda 不用担心,我们大多数人都会遇到这种情况。托尼的幸运日:)
【解决方案2】:

这并不完全是一个修复,但允许您测试在所有代码之外抽象的连接字符串,以至少验证您的连接字符串本身是否正常工作。这也应该为您提供一种更快地测试它的方法.. 发回您的发现,我会看看我是否可以做出更多贡献。

在使用 LinqPad 的服务器上,或者从技术上讲,您可以在您的应用程序中创建一个带有文本框的测试页面,以便您粘贴您的连接字符串进行测试,然后针对以下代码运行它。

using(var conn = new SqlConnection("Connection String Here"))
conn.Open();

这是所需的最少代码,如果您可以使用当前的连接字符串使其工作,您就知道正在发生其他事情,否则它为您提供了一个快速的方法来戳它直到它工作。

【讨论】:

    猜你喜欢
    • 2011-12-30
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    • 2012-11-06
    • 2016-06-01
    相关资源
    最近更新 更多