在 ASP.NET Core 7 WebAPI 上运行 React-App 构建

问题描述 投票:0回答:1

我有一个 ASP.NET Core 7 WebAPI,有很多路由,例如:

  • domain.com/Api/Product/GetAll
  • domain.com/Api/Product/Delete/
  • domain.com/Api/Product/Create
  • ...

我有一个反应应用程序,我需要使用它在我的 ASP 服务器上运行的构建文件夹,例如:

  • domain.com/my-react-app

我的意思是我想使用我的ASP作为react-app服务器,我该怎么做?

我的程序.cs:

using Microsoft.Extensions.FileProviders;

string WEB_ROOT_PATH = "Images";

var builder = WebApplication.CreateBuilder(
    new WebApplicationOptions { WebRootPath = WEB_ROOT_PATH }
);

string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
builder.Services.AddControllers();
builder.Services.AddCors(options =>
{
    options.AddPolicy(
        name: MyAllowSpecificOrigins,
        policy =>
        {
            policy.WithOrigins("*").AllowAnyHeader().AllowAnyMethod();
        }
    );
});

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}
app.UseCors(MyAllowSpecificOrigins);
app.MapGet("/", () => "ok");
app.MapGet("/CheckLocalServer", () => "ok");
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseStaticFiles(
    new StaticFileOptions
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(builder.Environment.ContentRootPath, "Images")
        ),
        RequestPath = "/Upload"
    }
);
app.UseAuthorization();

app.MapControllers();

app.Run();

我的包裹:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
    <Nullable>disable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.12" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.14" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.14">
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
      <PrivateAssets>all</PrivateAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.14" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
  </ItemGroup>

  <ItemGroup>
    <Folder Include="Sync\NewFolder\" />
  </ItemGroup>

</Project>
c# asp.net asp.net-core-webapi create-react-app asp.net-core-7.0
1个回答
0
投票

将webapi发布到文件夹后,在根目录中创建一个新文件夹“wwwroot”。
发布反应应用程序“npm run build”后,将所有发布的文件复制到“wwwroot”文件夹。

然后运行发布的webapplication.exe,就可以在同一个端口访问api和react页面了。
使用“create-react-app”模板和“dotnet new webapi”模板进行测试(添加

app.UseStaticFiles();
):

© www.soinside.com 2019 - 2024. All rights reserved.