在运行我的.NET 6 Web API作为自包含的服务时,如何防止404?

发布于 2025-01-18 18:47:38 字数 2440 浏览 2 评论 0 原文

我制作了一个简单的.NET 6 Web API。从Visual Studio运行(仅按F5)运行时,这可以正常工作。但是,在运行我的应用程序作为独立服务时,我会收到404的通话,这些电话应该成功。我如何确保我的独立服务开始行为相同?

这是我的 program.json

using Microsoft.Extensions.Hosting.WindowsServices;


var options = new WebApplicationOptions
{
    Args = args,
    ContentRootPath = WindowsServiceHelpers.IsWindowsService() ? AppContext.BaseDirectory : default
};

var builder = WebApplication.CreateBuilder(options);
builder.Services.AddRazorPages();

builder.Host.UseWindowsService();

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.MapControllers();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
//app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); });


await app.RunAsync();

这是我的 csproj


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

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
      <ImplicitUsings>enable</ImplicitUsings>
      <IsTransformWebConfigDisabled>true</IsTransformWebConfigDisabled>
      <RuntimeIdentifier>win-x64</RuntimeIdentifier>
    <UserSecretsId>XXXXX-78E75397-5A01-4397-9481-E423B4BF54C2</UserSecretsId>
  </PropertyGroup>

    <ItemGroup>
        <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
        <PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
        <PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="6.0.0" />
    </ItemGroup>
</Project>

这是我测试的方式:

  1. 打开解决方案文件并按F5。
  2. 运行 dotnet Publish -no -Build -c Release 从文件夹中执行了使用CSPROJ。这将在side xxxxx \ bin \ repares \ net6.0 \ win-x64 中生成一个exe,因此我通过从命令提示符转到此文件夹,然后运行exe来运行此文件夹。

在这两种情况下,我都使用 curl -i http:// localhost:5000/swagger/index.html 进行测试。

执行选项2时,这将返回404(使用 dotnet Publish )。从Visual Studio跑步时,我只是得到200个。

如何确保 dotnet Publish 的结果与我的应用程序从Visual Studio运行时的行为相同?

I have made a simple .NET 6 Web API. This works fine when running from Visual Studio (by just pressing F5). However, when running my application as a self-contained service I get a 404 for calls that are supposed to succeed. How can I make sure my self-contained service starts behaving the same?

Here is my Program.json

using Microsoft.Extensions.Hosting.WindowsServices;


var options = new WebApplicationOptions
{
    Args = args,
    ContentRootPath = WindowsServiceHelpers.IsWindowsService() ? AppContext.BaseDirectory : default
};

var builder = WebApplication.CreateBuilder(options);
builder.Services.AddRazorPages();

builder.Host.UseWindowsService();

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.MapControllers();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
//app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); });


await app.RunAsync();

Here is my csproj


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

  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
      <ImplicitUsings>enable</ImplicitUsings>
      <IsTransformWebConfigDisabled>true</IsTransformWebConfigDisabled>
      <RuntimeIdentifier>win-x64</RuntimeIdentifier>
    <UserSecretsId>XXXXX-78E75397-5A01-4397-9481-E423B4BF54C2</UserSecretsId>
  </PropertyGroup>

    <ItemGroup>
        <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
        <PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
        <PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="6.0.0" />
    </ItemGroup>
</Project>

This is how I test:

  1. Open the solution file and press F5.
  2. Run dotnet publish --no-build -c Release executed from the folder with the csproj in it. This generates an exe in side XXXXX\bin\Release\net6.0\win-x64 so I run the exe from this folder by going to this folder from the command prompt and then run the exe.

In both situations, I test using curl -I http://localhost:5000/swagger/index.html .

This returns a 404 when doing option 2 (with dotnet publish). When running from visual studio, I just get a 200.

How to make sure the result of dotnet publish behaves the same as my application behaves when running from Visual Studio?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

掩于岁月 2025-01-25 18:47:38

在这两种情况下,该服务都是自托管的。另一种选择是使用 IIS。

Swagger 被禁用的原因是代码仅在开发环境中显式启用它。

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

环境由 ASPNETCORE_ENVIRONMENT 环境变量的值控制。除非您在用户或系统的环境变量中显式设置该环境变量,否则它不会存在,并且您的服务将以生产模式运行。

Shell 脚本通常在执行依赖于环境变量的程序之前设置环境变量。 Visual Studio 在启动程序之前设置 launchsettings.json 中指定的环境变量。如果您尝试在 VS 之外运行该程序,您必须自己设置它们,例如:

SET ASPNETCORE_ENVIRONMENT=Development

myservice.exe

launchsettings.json 用于 指定启动配置文件,而不仅仅是环境变量。这包括托管模型、命令行参数等等。通常它由 Visual Studio 等 IDE 使用,但您也可以使用 dotnet run 使用带有 --launch-profile 选项的特定配置

文件 文档解释说此文件未部署,因此它永远不会出现在这发布文件夹:

launchSettings.json 文件:

  • 仅在本地开发计算机上使用。
  • 未部署。
  • 包含个人资料设置。

The service is self-hosted in both cases. The other option would be to use IIS.

The reason Swagger is disabled is because the code explicitly enables it only in a development environment.

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

The environment is controlled by the value of the ASPNETCORE_ENVIRONMENT environment variable. Unless you explicitly set that environment variable in a user's or system's Environment Variables, it won't exist, and your service will run in Production mode.

Shell scripts often set environment variables before executing programs that depend on them. Visual Studio sets the environment variables specified in launchsettings.json before launching your program. If you try to run the program outside VS you'll have to set them yourself, eg:

SET ASPNETCORE_ENVIRONMENT=Development

myservice.exe

launchsettings.json is used to specify launch profiles, not just environment variables. This includes the hosting model, command line arguments and more. Typically it's used by an IDE like Visual Studio but you can also launch a .NET program with dotnet run using a specific profile with the --launch-profile <NAME> option

The docs explain that this file isn't deployed, so it never appears in the publish folder:

The launchSettings.json file:

  • Is only used on the local development machine.
  • Is not deployed.
  • Contains profile settings.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文