找不到试图导航到我的 asp.net 核心 5.0 Web 服务的页面

Getting page not found trying to navigate to my asp.net core 5.0 web service

我使用 .Net 5.0 创建了一个新的 ASP.NET Core Razor 项目,我创建了一个简单的 Web 服务 API 页面,如下所示。问题是当我 运行 它然后在浏览器中我调用 http://localhost:50050/api/test 我得到“HTTP ERROR 404*”意味着我的网络服务找不到。我有一个类似的应用程序刚刚在旧版本的 .net core 中完成并且工作得很好。有谁知道我做错了什么?

using Microsoft.AspNetCore.Mvc;

namespace WebApplication2.Api
{
    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        [HttpGet]
        public int GetTest()
        {
            return 21;
        }

        [HttpGet("{id}")]
        public int GetTest([FromRoute] int id)
        {
            return 22;
        }
    }
}

启动页面如下图:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication2
{
    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.AddRazorPages();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
            });
        }
    }
}

下面是我的项目布局

您只有一个端点到您的 RazorPages,而不是您的控制器。

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
        });

您需要做的是在 Startup ConfigureServices 方法中注册您的控制器:

public void ConfigureServices(IServiceCollection services)
{
     services.AddControllers();
}

然后像这样在端点中间件中添加这些控制器:

public void Configure(IApplicationBuilder app){
   // other middlewares
   app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllers();
            });
}