首页 > 解决方案 > 在相同的解决方案问题中使用 create-react-app 前端创建 .NET Core 3.0 WebAPI 时出错

问题描述

我尝试了几种不同的方法来设置这个项目,但每一种都失败了。这是我的问题。

这是我的 startup.cs 代码:

   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.AddMvc().AddNewtonsoftJson();

        services.AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "client/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();
        }
        else
        {
            // 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.UseRouting(routes =>
        {
            routes.MapControllers();
        });

        app.UseSpa(spa =>
        {
            spa.Options.SourcePath = "client";
            if (env.IsDevelopment())
            {
                spa.UseReactDevelopmentServer(npmScript: "start");
            }
        });

        app.UseAuthorization();
    }
}

当我运行它时,spa.UserReactDevelopmentServer(npmScript: "start")的行不断抛出错误。错误是:

{“找不到方法:'无效 Microsoft.Extensions.Logging.Console.ConsoleLogger..ctor(System.String, System.Func`3, Boolean)'。”}

有没有人知道如何使用 React 前端(不是类型脚本版本)创建一个 .NET Core 3.0 WebAPI,当你点击播放时(VS 2019 中的绿色继续按钮)运行 React 并且仍然有 API 部分调用它时工作。看在上帝的份上,不应该这么难!!

标签: asp.net-core-webapicreate-react-app.net-core-3.0

解决方案


我遇到过同样的问题。

将项目 .csproj 中“Microsoft.AspNetCore.SpaServices.Extensions”的参考版本更改为“3.0.0-preview8.19405.4”对我有用。


推荐阅读