【问题标题】:ASP.NET Core 5.0 application using React.js and MySQL as Database使用 React.js 和 MySQL 作为数据库的 ASP.NET Core 5.0 应用程序
【发布时间】:2021-12-09 18:57:02
【问题描述】:

最近我正在尝试使用 React.js 的新 ASP.NET Core 5.0。我想使用 MySql 作为我的数据库服务器。

现在我想使用我们以前在 ASP.NET 版本中使用的 ASP.NET Identity Server for Membership。

我尝试按照此处列出的教程进行操作:Video Link

现在在 appsettings.json 中是代码

{
  "ConnectionStrings": {
    "DefaultConnection": "server=localhost; port=3306; database=trom; user=root; password=hello@world; CharSet=utf-8"
  },
  "Logging": {
      "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
      }
    },
  "IdentityServer": {
    "Clients": {
      "Trom": {
        "Profile": "IdentityServerSPA"
      }
    }
  },
"AllowedHosts": "*"
}

现在在 Startup.cs 中,我正在尝试按照视频中的建议进行更改

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Trom.Data;
using Trom.Models;

namespace Trom
{
    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.AddDbContext<ApplicationDbContext>(options =>
                options.UseMySql(
                    Configuration.GetConnectionString("DefaultConnection")));

            services.AddDatabaseDeveloperPageExceptionFilter();

            services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.AddIdentityServer()
                .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();

            services.AddAuthentication()
                .AddIdentityServerJwt();

            services.AddControllersWithViews();
            services.AddRazorPages();

            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/build";
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseMigrationsEndPoint();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            app.UseIdentityServer();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
            });

            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseReactDevelopmentServer(npmScript: "start");
                }
            });
        }
    }
}

我得到的错误是

文档网站上有很多方法建议。但似乎没有任何效果。有什么解决方法吗?

【问题讨论】:

    标签: mysql reactjs mysql-connector asp.net-core-5.0 pomelo-entityframeworkcore-mysql


    【解决方案1】:

    视频有点旧,使用 EF Core 3.0 的 Pomelo 版本。

    对于 5.0,请查看我们在 repository 主页上显示的 sample code

    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            // Replace with your connection string.
            var connectionString = "server=localhost;user=root;password=1234;database=ef";
    
            // Replace with your server version and type.
            // Use 'MariaDbServerVersion' for MariaDB.
            // Alternatively, use 'ServerVersion.AutoDetect(connectionString)'.
            // For common usages, see pull request #1233.
            var serverVersion = new MySqlServerVersion(new Version(8, 0, 26));
    
            // Replace 'YourDbContext' with the name of your own DbContext derived class.
            services.AddDbContext<YourDbContext>(
                dbContextOptions => dbContextOptions
                    .UseMySql(connectionString, serverVersion)
                    // The following three options help with debugging, but should
                    // be changed or removed for production.
                    .LogTo(Console.WriteLine, LogLevel.Information);
                    .EnableSensitiveDataLogging()
                    .EnableDetailedErrors()
            );
        }
    }
    

    对于您上面发布的代码,这转换为:

    var connectionString = Configuration.GetConnectionString("DefaultConnection");
    var serverVersion = ServerVersion.AutoDetect(connectionString);
    
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseMySql(connectionString, serverVersion));
    

    我们在 5.0 中为 UseMySql() 方法添加了一个强制性的 ServerVersion 参数,因为 Pomelo 将使用更新的功能,具体取决于您使用的 MySQL/MariaDB 版本。

    【讨论】:

      猜你喜欢
      • 2021-09-30
      • 1970-01-01
      • 1970-01-01
      • 2013-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-03
      相关资源
      最近更新 更多