ASP.NET core web api returns 404 when Startup.cs in different assembly

不想你离开。 提交于 2020-06-16 05:07:44

问题


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.

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

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

So I need to put startup class in a different assembly and then use it inside multiple Web API projects


回答1:


Replace the .UseStartup with the following lines:

.UseStartup<Application.AppComponents.Startup>() 
.UseSetting(WebHostDefaults.ApplicationKey, typeof(Program).GetTypeInfo().Assembly.FullName)

Where Application.AppComponents.Startup is the namespace of your startup file in the class library.



来源:https://stackoverflow.com/questions/55204707/asp-net-core-web-api-returns-404-when-startup-cs-in-different-assembly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!