我有以下设置:
这很简单。现在我面临的情况很奇怪。如果将启动文件放在 Test 项目中,则所有路由都将得到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类更加奇怪。
答案 0 :(得分:2)
我让它工作了,这是修复它的原因:
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(); }