WebApi 在调试时给出 404;发布时有效

WebApi giving 404 whilst debugging; works when published

我有一个用 .NET Core 2.2.6 编写的控制台应用程序,它使用 Kestrel 托管一个简单的 WebApi。

public class SettingsController : Controller
{
    // 
    // GET: /settings/

    public string Index()
    {
        return $"Hello world! controller";
    }
}

如果我发布代码和 运行 可执行文件,我可以访问 http://127.0.0.1:310/settings 并看到预期的 "Hello world! controller"。但是,如果我从 Visual Studio 2019 内部调试(甚至在发布模式下打开),相同的 URL 会引发 404 异常。

可能有助于查明问题的其他一些代码:

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
    WebHost.CreateDefaultBuilder(args)
        .ConfigureKestrel((context, options) =>
        {
            options.ListenAnyIP(310, listenOptions =>
            {
                listenOptions.Protocols = HttpProtocols.Http1;
            });
        })
        .UseStartup<Startup>();

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseDefaultFiles(new DefaultFilesOptions()
        {
            DefaultFileNames = new List<string>() { "index.html" }
        });

        // Return static files and end the pipeline.
        app.UseStaticFiles(new StaticFileOptions
        {
            OnPrepareResponse = ctx =>
            {
                const int durationInSeconds = 60 * 60 * 24;
                ctx.Context.Response.Headers[HeaderNames.CacheControl] =
                    "public,max-age=" + durationInSeconds;
            }
        });

        // Use Cookie Policy Middleware to conform to EU General Data 
        // Protection Regulation (GDPR) regulations.
        app.UseCookiePolicy();

        // Add MVC to the request pipeline.
        app.UseMvcWithDefaultRoute();
    }
}

有一个非常相关的 GitHub issue 解释了这里发生的事情。 ASP.NET 核心团队的 Pranav K 说:

MVC 2.1.0 requires compilation context to be available. Compilation context tells it if a library references MVC which is used as a filter to skip assemblies that are deemed unlikely to have controllers. Microsoft.NET.Sdk does not set <PreserveCompilationContext>true</PreserveCompilationContext> which would explain why you're seeing this.

这意味着您遇到的问题有几个可行的解决方案:

  1. PreserveCompilationContext 属性 添加到您的 .csproj 文件中,值为 true,如上所示。
  2. 引用 Microsoft.NET.Sdk.Web 项目 SDK 而不是 Microsoft.NET.Sdk

我不知道这两个选项之间有什么明显的区别,但我会更新项目 SDK,因为它实际上是您正在构建的 Web 项目。