c# - 当不同程序集中的 Startup.cs 时,ASP.NET Core Web API 返回 404

标签 c# asp.net-core .net-core asp.net-core-webapi

我有 .net 核心 Web API,当我在不同的程序集中隔离 Startup.cs 时,所有 API 都返回 404,如果我将 Startup.cs 返回到同一个程序集在 Controller 存在的地方,它们再次工作。

这是我的 Web API 的 Program.cs:

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:

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 项目中使用它

最佳答案

.UseStartup 替换为以下行:

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

其中 Application.AppComponents.Startup 是您的启动文件在类库中的命名空间。

关于c# - 当不同程序集中的 Startup.cs 时,ASP.NET Core Web API 返回 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55204707/

相关文章:

c# - C#中的组合算法

c# - IOptions 不适用于 TinyIOC/NancyFX

visual-studio - 在后台拥有 npm 监视文件以启用与 Visual Studio Task Runner 的集成

c# - 选择 ComboBox 中的项目会影响不相关的 ComboBox

c# - 从字符串中提取所有出现的特定字符

ms-access - .NET Core 中的 MS Access 数据库

c# - .netcore 中的 HttpClient 会自动在 header 中添加一个空格

mysql - IDbConnection 与 .Net Core 中的 MySql - 无法使用 autofac 注入(inject)

c# - 缩略图视频 C#

visual-studio - 从 Visual Studio 2019 将 ASP.NET Core 3.1 站点发布到 Azure 时出错