问题描述
我具有.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
:
.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.
这篇关于当Startup.cs在不同的程序集中时,ASP.NET Core Web API返回404的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!