gpt4 book ai didi

c# - 从控制台应用程序启动 ASP.NET Core Web API

转载 作者:行者123 更新时间:2023-12-02 01:26:07 26 4
gpt4 key购买 nike

我想将 ASP.NET Core WebApi 集成到包含许多其他项目的解决方案中。(我使用的是 dotnet 6.0)在解决方案中,WebAPI 由 Main 项目作为 Thread 启动。问题是,如果我从其他项目运行 WebApi,则只会启动一个空的 WebApi。 (使用默认端口,而不是配置的端口,并且没有 Controller ...)

谁能帮帮我?

这是我上面描述的相同问题的最小解决方案:

Solution structure

WebApi 是默认的 VisualStudio 2022 项目。我只对 Program.cs 文件做了一些小改动。这是 WebApi 项目的 Program.cs 文件的代码:

namespace WebApi;

public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

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();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();
}
}

主工程Programm.cs代码:

using WebApi;

internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
WebApi.Program.Main(Array.Empty<string>());
}
}

launchSettings.json

{
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:56423",
"sslPort": 44385
}
},
"profiles": {
"WebApi": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7257;http://localhost:5257",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

这是我从主项目运行 WebApi 时的样子:

Hello, World!
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[14]
Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
Content root path: C:\data\Experimental\CallWebApiFromOtherProject\Main\bin\Debug\net6.0\

( Controller 和 Swagger 不可用。端口也不是上面定义的端口。-> 只有一个没有任何东西的 Web 服务器)

我做错了什么?

最佳答案

部分配置丢失,因为你从其他项目启动webapi您可以在 WebApi 的 main 方法中尝试如下:

Directory.SetCurrentDirectory(@"the directory of WebApi Project");
var builder = WebApplication.CreateBuilder(new WebApplicationOptions() { EnvironmentName= "Development",ApplicationName="WebApi"});

现在,它在我的情况下运行良好:

enter image description here

关于c# - 从控制台应用程序启动 ASP.NET Core Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74631799/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com