asp.net-core-webapi - 在相同的解决方案问题中使用 create-react-app 前端创建 .NET Core 3.0 WebAPI 时出错
问题描述
我尝试了几种不同的方法来设置这个项目,但每一种都失败了。这是我的问题。
- 使用命令提示符按照本文的指示创建这些项目有一个主要缺陷,如果您生成这些项目,然后在 VS 2019 中打开它,您可以开箱即用地运行它,没有问题。第二次添加文件,它会提示您保存解决方案文件,之后,整个解决方案崩溃,您无法再启动它....所以这个选项似乎很糟糕。
- 我尝试使用 VS 2019 创建一个 .net core 3 应用程序,使其成为 WebAPI 应用程序。之后,我进入根目录并通过命令提示符写道: npx create-react-app client似乎可以正确创建项目。之后,我在 startup.cs 文件中添加了运行所需的 spa 项目(添加了 NuGet 包 Microsoft.AspNetCore.SpaServices.Extensions)
这是我的 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 部分调用它时工作。看在上帝的份上,不应该这么难!!
解决方案
我遇到过同样的问题。
将项目 .csproj 中“Microsoft.AspNetCore.SpaServices.Extensions”的参考版本更改为“3.0.0-preview8.19405.4”对我有用。
推荐阅读
- javascript - React-Redux,如何在渲染新组件之前设置全局状态?
- typescript - 试图为 TypeScript EventListeners 建立一个泛型类型并得到一个奇怪的错误
- flutter - 为什么我不能在颤振中访问 Firestore 值?
- r - 将大型 zip tsv 文件导入 R 时出现内存问题
- reactjs - Redirect from 在反应路由器中意味着什么
- c# - 为什么我不能使用他们提供的示例通过 mapbox api 创建一个有效的样式?
- c# - 在不使用 app.config 的情况下将连接字符串传递给 DBcontext
- vim - 键入 ')' 并且光标下的字符为 ')' 时向右移动光标
- mariadb - 数据库优化
- python - 为什么无法汇总利润?列表值有问题吗?