首页 > 解决方案 > 路由未初始化

问题描述

我有以下设置:

解决方案结构

这很简单。现在我面临的情况很奇怪。如果我将启动文件放在测试项目中,我会得到所有路由的 404,如果我将该文件移动到WebApplication1 ,则会找到所有路由。

这是 Startup 类的样子:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Swashbuckle.AspNetCore.Swagger;

namespace Test
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), 
            // specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });

            app.UseMvc();
        }
    }
}

我不能提供更多细节,因为这就是我所拥有的。将课程从一个项目转移到另一个项目会产生问题,我不明白为什么。

测试项目只是一个类库:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
    <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore" Version="2.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.1" />
    <PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="3.0.0" />
    <PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="3.0.0" />
    <PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="3.0.0" />
  </ItemGroup>

</Project>

更新

为了清楚起见,问题是为什么将 Startup 类移动到 Test 项目会停止初始化路由?

提前致谢。

更新

Test 项目实际上只是 Web 项目的一组通用基类,抱歉名称错误。因此,如果我将 Startup 类从 Common.Web 项目移动到 WebApplication1 并更新命名空间一切正常,否则会阻止它工作。调试显示正在调用 Startup 类,这更加奇怪。

解决方案结构

标签: c#asp.net-core

解决方案


我让它工作了,这就是修复它的原因:

public virtual void ConfigureServices(IServiceCollection services)
{
    var mvcModule = services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    foreach(var assembly in EndpointAssemblies)
    {
        mvcModule.AddApplicationPart(assembly);
    }

EndpointAssemblies 只是已定义程序集的列表。mvcModule.AddControllersAsServices(); }


推荐阅读