首页 > 解决方案 > ASP.NET Core 2.2 Web API 没有命中任何配置的路由,这是为什么呢?

问题描述

我创建了看起来像这样的 BaseController

`[ApiController]
  public class MoviesPlaceBaseController : ControllerBase
  {
    protected readonly IMoviesPlaceSupervisor _moviesPlaceSupervisor;

    public MoviesPlaceBaseController(IMoviesPlaceSupervisor moviesPlaceSupervisor)    
    {
        _moviesPlaceSupervisor = moviesPlaceSupervisor;
    }`

在我的“PostController”中,我从那个看起来像这样的基本控制器类派生

`    [Route("[controller]")]
    [Produces("application/json")]
    public class PostController : MoviesPlaceBaseController
    {
      public PostController(IMoviesPlaceSupervisor supervisor) : base (supervisor){ }

        // GET api/post
        [HttpGet]
        [Produces(typeof(List<PostViewModel>))]
        public async Task<ActionResult<List<PostViewModel>>> Get(CancellationToken ct = default(CancellationToken))
        {
          return new ObjectResult(await _moviesPlaceSupervisor.GetAllPostsAsync(ct));
        }`

我的launchSettings.json 我删除了https url,现在看起来像这样

`"MoviesPlaceAPI": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "api/",
      "applicationUrl": "http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }`

我的 Startup.cs ConfigureServices 看起来像这样

` public void ConfigureServices(IServiceCollection services)
    {
      services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

      services.AddConnectionProvider(Configuration)
        .ConfigureSupervisor()
        .AddMiddleware()
        .AddCorsConfiguration()
        .ConfigureRepositories();
    }`

运行我的应用程序时,我无法点击我的 api/post 路由。当我在该操作中放置断点并运行应用程序时,断点显示其“未验证”。我尝试做 api/post 和 api/posts。在控制器类中,我删除了仅带有控制器“post”名称的 Route[“controller”],但同样的事情。奇怪的是我可以很好地点击 api/values,即使该控制器不再存在于我的应用程序中。我不知道发生了什么,请有人能阐明一下。

标签: c#asp.net-web-apiasp.net-core.net-core

解决方案


当我执行干净然后构建时,我将我的项目从 asp.net core 2.1 升级到 2.2。它并没有完全摆脱以前编译的代码。我的 launch.json 文件仍然指向 Debug/netcoreapp.2.1... 在将其更改为 2.2 之后,一切都开始按预期工作。


推荐阅读