代码之家  ›  专栏  ›  技术社区  ›  Ms01

在razor页面应用程序中路由到apicontroller?

  •  6
  • Ms01  · 技术社区  · 6 年前

    我创建了一个ASP.NET核心剃须刀页面应用程序(ASP.NET版)。它的工作正常,与正常的网页,但我也想要一个附注器,如本教程: 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();
            }
    

    我的助手类:

        [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)}};
            }
    }
    

    据我所见,一切都像指南,但显然有些地方是不正确的,因为我得到404的所有页面。即使我创建了一个新的方法,但它并没有真正达到预期的效果,而且是无法实现的。

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

    提前谢谢你的帮助!

    1 回复  |  直到 6 年前
        1
  •  4
  •   CodeNotFound dotnetstep    6 年前

    你需要一个公共控制器类。

    所以不是:

    [Route("api/[controller]")]
    [ApiController]
    class DomainController : ControllerBase
    {
        [...]
    } 
    

    你应该有这个:

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