在剃须刀页面应用程序中路由到ApiController?

Ms0*_*s01 6 c# asp.net-core asp.net-core-webapi razor-pages

我创建了一个ASP.NET Core Razor页面应用程序(asp.net版本2.1.1).它适用于普通的页面,但我也想要一个ApiController,如本教程:https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-vsc?view = aspnetcore-2.1

但是,当我像上面的示例中那样创建控制器时,每当我尝试访问它时,我会得到一个404页面.

启动类中是否有我遗漏的东西?

public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext<DomainDbContext>(opt => opt.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

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

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc();
        }
Run Code Online (Sandbox Code Playgroud)

我的apicontroller类:

    [Route("api/[controller]")]
    [ApiController]
    class DomainController : ControllerBase 
    {
        private readonly DomainDbContext _context;

        public DomainController (DomainDbContext context) 
        {
            _context = context;
        }

        [HttpGet]
        public ActionResult<List<Domain>> GetAll()
        {
            return new List<Domain> {new Domain() {Name ="Hello", Tld = ".se", Expiration = DateTime.UtcNow.AddDays(35)}};
        }
}
Run Code Online (Sandbox Code Playgroud)

就我所见,所有东西看起来都像指南,但显然有些东西不正确,因为我得到所有页面的404.即使我创建了一个新方法,它也没有真正按预期工作并且无法访问.

我试过的主要途径是/api/domain.

感谢您的帮助!

小智 11

只需将 endpoints.MapControllers() 添加到 UseEndpoints 选项即可:

app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllers();
            });
Run Code Online (Sandbox Code Playgroud)


Cod*_*und 7

您需要有一个公共控制器类。

所以而不是:

[Route("api/[controller]")]
[ApiController]
class DomainController : ControllerBase
{
    [...]
} 
Run Code Online (Sandbox Code Playgroud)

你应该有这个:

[Route("api/[controller]")]
[ApiController]
public class DomainController : ControllerBase // <-- add a public keyword
{
    [...]
} 
Run Code Online (Sandbox Code Playgroud)