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

Mar*_*nti 4 c# .net-core kestrel-http-server asp.net-core asp.net-core-webapi

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

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

    public string Index()
    {
        return $"Hello world! controller";
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我发布代码并运行可执行文件,我可以访问http://127.0.0.1:310/settings并看到预期的“Hello world!控制器”。但是,如果我从 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Kir*_*kin 5

有一个非常相关的GitHub 问题可以解释这里发生的事情。来自 ASP.NET Core 团队的 Pranav K 说:

MVC 2.1.0 要求编译上下文可用。编译上下文告诉它一个库是否引用了 MVC,MVC 被用作过滤器来跳过被认为不太可能有控制器的程序集。Microsoft.NET.Sdk 没有设置<PreserveCompilationContext>true</PreserveCompilationContext>,这可以解释为什么你会看到这个。

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

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

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