问题描述
我有 .net 核心 Web API,当我在不同的程序集中隔离 Startup.cs 时,所有 API 都返回 404,如果我将 Startup.cs 返回到同一个程序集在控制器存在的地方,它们会再次工作.
I have .net core web API and when I isolated Startup.cs in different assembly all APIs return 404 and if I return Startup.cs back to the same assembly where controllers exist, they work again.
这是我的 Web API 的 Program.cs:
Here is my Program.cs of my web API:
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureAppConfiguration((hostContext, configApp) =>
{
configApp.SetBasePath(Directory.GetCurrentDirectory());
configApp.AddJsonFile("appsettings.json", false, true);
configApp.AddJsonFile($"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", false, true);
});
}
还有我的 Startup.cs :
And my Startup.cs :
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddDataAnnotationsLocalization(options =>
{
options.DataAnnotationLocalizerProvider = (type, factory) =>
factory.Create(typeof(ValidationMessages));
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
}
所以我需要将启动类放在不同的程序集中,然后在多个 Web API 项目中使用它
So I need to put startup class in a different assembly and then use it inside multiple Web API projects
推荐答案
将 .UseStartup
替换为以下几行:
Replace the .UseStartup
with the following lines:
.UseStartup<Application.AppComponents.Startup>()
.UseSetting(WebHostDefaults.ApplicationKey, typeof(Program).GetTypeInfo().Assembly.FullName)
其中 Application.AppComponents.Startup
是类库中启动文件的命名空间.
Where Application.AppComponents.Startup
is the namespace of your startup file in the class library.
这篇关于ASP.NET 核心 Web api 在不同程序集中的 Startup.cs 时返回 404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!