【问题标题】:Razor page is messing up the encoding when assigning special character to string将特殊字符分配给字符串时,剃刀页面弄乱了编码
【发布时间】:2019-11-19 04:01:46
【问题描述】:

更新 4:

哇哦,显然这不是 EF 或配置问题。

Somehow the .razor page variable assigment is messing up the data.

现在不知道如何处理这个问题,但我至少编辑了标题以反映当前问题,即:Razor page is messing up the encoding when assignment special character to string.


问题:

无论我做什么,我插入 MySQL 5.7.17 数据库的字符总是显示为 �:

Database lookup

虽然有类似的帖子,但没有一个解决方案对我有用,我已经用尽了我的研究能力。

我尝试过的:

代码:

连接字符串:

"MySQL": "server=localhost;user=root;database=sgn;charset=utf8mb4;"

UserModel.cs

namespace source.Data.Models
{
    [MySqlCharset("utf8mb4")]
    [MySqlCollation("utf8mb4_unicode_ci")]
    public class UserModel
    {
        public UserModel() { }

        [Key]
        public long Id { get; set; }
        [MySqlCharset("utf8mb4")]
        [MySqlCollation("utf8mb4_unicode_ci")]
        public string Username { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Language { get; set; }
        public string StartPage { get; set; }
    }
}

DatabaseContext.cs

namespace source.Data.Database
{
    public class DatabaseContext : DbContext
    {
        private IConfiguration Configuration;
        public DbSet<UserModel> Users { get; set; }

        public DatabaseContext(DbContextOptions<DatabaseContext> options, IConfiguration configuration)
            : base(options)
        {
            Configuration = configuration;
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder
                .UseMySQL(Configuration.GetSection("AppSettings").GetSection("Database").GetSection("ConnectionString")["MySQL"]);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<UserModel>().Property(p => p.Username).IsUnicode(true);
            base.OnModelCreating(modelBuilder);
        }

    }
}

DesignTimeDatabaseContextFactory.cs

namespace source.Data.Database
{
    public class DesignTimeDatabaseContextFactory : IDesignTimeDbContextFactory<DatabaseContext>
    {
        private IConfiguration Configuration;
        private AppSettingsService AppSettings;

        public DesignTimeDatabaseContextFactory()
        {
        }

        public DesignTimeDatabaseContextFactory(IConfiguration configuration, AppSettingsService appSettings)
        {
            Configuration = configuration;
            AppSettings = appSettings;
        }

        public DatabaseContext CreateDbContext(string[] args)
        {
            var builder = new DbContextOptionsBuilder<DatabaseContext>();

            builder.UseMySQL(AppSettings.ConnectionString);


            return new DatabaseContext(builder.Options, Configuration);
        }
    }
}

Create.razor - 这是我将用户添加到数据库的地方。请注意,此项目使用 Blazor,因此不要被“@functions”标签混淆。这两个函数都没有正确添加数据,并且注释的是我尝试过的准备好的语句。

<div class="login_form">
    <h3>Create Account</h3>

    <button @onclick="@(e => AddEntry())">Add DB User!</button><br />
    <button @onclick="@(e => AddEntry2())">Add TEST!</button><br />
</div>

@functions {

    void AddEntry2()
    {
        UserModel test = new UserModel();

        test.Username = "Test çã";
        test.FirstName = "Michel";
        test.LastName = "Arendt";
        test.Email = "mail@gmail.com";
        test.Password = "123";
        test.Language = "pt-BR";
        test.StartPage = "/Home/";

        db.Database.ExecuteSqlCommand("SET NAMES utf8mb4");
        db.Database.ExecuteSqlCommand("SET character_set_connection = utf8mb4");
        db.Database.ExecuteSqlCommand("INSERT INTO Users (Username) VALUES (N'" + test.Username + "')");
        db.SaveChanges();


        //using (SqlConnection connection = new SqlConnection(AppSettings.DatabaseConnectionString()))
        //{
        //    connection.Open();
        //    SqlCommand command = new SqlCommand(null, connection);

        //    // Create and prepare an SQL statement.
        //    command.CommandText =
        //        "INSERT INTO Users (Username) " +
        //        "VALUES (@username)";
        //    SqlParameter username = new SqlParameter("@username", SqlDbType.NVarChar, 100);
        //    username.Value = "Garçon";
        //    command.Parameters.Add(username);

        //    // Call Prepare after setting the Commandtext and Parameters.
        //    command.Prepare();
        //    command.ExecuteNonQuery();
        //}
    }

    void AddEntry()
    {
        UserModel waitress = new UserModel();

        waitress.Username = "Garçon";
        waitress.FirstName = "Test";
        waitress.LastName = "Test";
        waitress.Email = "mail@gmail.com";
        waitress.Password = "123";
        waitress.Language = "pt-BR";
        waitress.StartPage = "/Home/";

        db.Users.Add(waitress);
        db.SaveChanges();
    }
}

source.csproj(依赖项参考)

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.0</TargetFramework>
    <LangVersion>7.3</LangVersion>
    <RestorePackages>false</RestorePackages>
    <Version>0.10.0</Version>
    <Authors>Michel Arendt</Authors>
    <Product>SGN</Product>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <DefineConstants>DEBUG;TRACE</DefineConstants>
    <DebugType>full</DebugType>
    <DebugSymbols>true</DebugSymbols>
  </PropertyGroup>
  <ItemGroup>
    <Content Remove="compilerconfig.json" />
  </ItemGroup>
  <ItemGroup>
    <None Include="compilerconfig.json" />
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="ElectronNET.API" Version="5.22.13" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.2.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.2.4" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.2.4">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0" />
    <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.0.0-preview6.19304.6" />
    <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.2.0" />
    <PackageReference Include="MySql.Data.EntityFrameworkCore" Version="8.0.16" />
    <PackageReference Include="System.Configuration.ConfigurationManager" Version="4.5.0" />
  </ItemGroup>
  <ItemGroup>
    <Content Update="electron.manifest.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </Content>
  </ItemGroup>
</Project>

数据库配置

数据库和列的默认排序规则和字符集分别为 utf8mb4_unicode_ci 和 utf8mb4:

Default database character set and collation

Columns character set and collation


对于我还可以尝试什么来解决此问题或我正在犯什么错误有什么想法吗?

提前致谢!


更新:

按照 Bradley Grainger(在 cmets 上)的建议,我切换到了 Pomelo.EntityFrameworkCore.MySql,但这无助于解决问题。我更改的文件现在是:

将构建从 Startup.csDesignTimeDatabaseContextFactory.cs 更改为使用:

builder
                .UseMySql(AppSettings.ConnectionString,
                    mysqlOptions =>
                    {
                        mysqlOptions
                            .CharSetBehavior(CharSetBehavior.AppendToAllColumns)
                            .AnsiCharSet(CharSet.Utf8mb4)
                            .UnicodeCharSet(CharSet.Utf8mb4);
                    });

Create.razor

void AddEntry2()
{
    UserModel test = new UserModel();

    test.Username = "Test çã";
    test.FirstName = "Michel";
    test.LastName = "Arendt";
    test.Email = "mail@gmail.com";
    test.Password = "123";
    test.Language = "pt-BR";
    test.StartPage = "/Home/";

    using (MySqlConnection connection = new MySqlConnection(AppSettings.ConnectionString))
    {
        connection.Open();
        MySqlCommand command = new MySqlCommand(null, connection);

        // Create and prepare an SQL statement.
        command.CommandText =
            "INSERT INTO Users (Username) " +
            "VALUES (@username)";
        MySqlParameter username = new MySqlParameter("@username", MySqlDbType.LongText, 100);
        username.Value = "Garçon";
        command.Parameters.Add(username);

        // Call Prepare after setting the Commandtext and Parameters.
        command.Prepare();
        command.ExecuteNonQuery();
    }
}

认为这会有所帮助,所以我还在本地服务器上设置了 MySQL 初始化 (my.ini) 以:

[mysqld]
character-set-server=utf8mb4
collation-server=utf8mb4_general_ci

但是,没有任何效果。还有其他想法吗?


更新 2:

为了确定是数据库还是 EF Core 问题,我设置了一个简单的 PHP 脚本来在数据库中插入相同的条目。

On this image entry 1 and 2 are inserted from EF Core while entry 3 was inserted from PHP

从图像中可以看出,数据库似乎很好,因为 PHP 的插入工作正常。

添加条目时如何确保EF Core使用的是“utf8mb4”编码?


【问题讨论】:

  • 您的数据库列类型和连接字符串看起来正确。 N'...' 前缀非常陈旧,在最近的 Connector/NET 版本中不需要。 (另外,您应该使用MySqlParameter,而不是文字SQL 来插入值。)我唯一的其他建议是尝试从MySql.Data.EntityFrameworkCore 切换到Pomelo.EntityFrameworkCore.MySql 作为您的MySQL EF Core 库;你会发现很多人报告说它更可靠,例如,stackoverflow.com/questions/46089982/…
  • @BradleyGrainger 显然不是 EF 的问题,而是 .razor 页面。
  • 你检查过剃须刀文件的编码吗?在所有示例中,插入语句的输入似乎直接来自剃须刀页面,而不是通过表单帖子或类似的方式
  • @ThomasSchmidt 确实如此。按照this question 的建议使用特定编码保存文件有效。我现在该如何处理这个问题?

标签: c# mysql razor entity-framework-core special-characters


【解决方案1】:

正如 Thomas Schmidt 在 OP 的 cmets 上所建议的那样,问题出在其他地方,我没有想到 Visual Studio 保存文件时使用的编码。这个问题描述了解决方案:

razor view » character rendered as »

解决方案:

选择您要更改编码的文件并点击文件菜单,然后将“PAGE”另存为,然后选择Save with Encoding...并选择所需的编码。


我已编辑帖子的问题标题以反映当前问题。让我知道是否应该将其更改回来,因为我不确定如何在此处继续。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多