在VS代码中使用C#和API.NET在http:// localhost:5000 / api /类别上获取404错误

问题描述 投票:0回答:1

我正在跟https://www.freecodecamp.org/news/an-awesome-guide-on-how-to-build-restful-apis-with-asp-net-core-87b818123e28/一起关注,这时,我应该在浏览器中输出此JSON数据。

[
  {
     "id": 100,
     "name": "Fruits and Vegetables",
     "products": []
  },
  {
     "id": 101,
     "name": "Dairy",
     "products": []
  }
]

但是,我在http://localhost:5000/api/categories上收到404错误。否则,一切似乎都很好,并且此时没有错误。我以前使用过MERN堆栈,因此我觉得我可能会注意到是否缺少端点或类似的东西。正因为如此,这是我对API.NET的first尝试,所以我真的很沮丧,并寻求帮助。与MERN一样,我不得不做很多软件包安装和版本修改工作,才能解决我在该项目中遇到的所有先前问题,他们已经解决了这些问题,因此我认为可能是类似的情况。谢谢你的帮助。项目位于GitHub Market-App,因为“类别”所依赖的文件不止几个。

c# rest google-api-dotnet-client
1个回答
0
投票

查看您的项目,您没有正确配置Startup类。

现在(从3.0开始,似乎是您的目标)建议使用endpoints instead of mvc。因此,您的启动应如下所示:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers(); // <-- this changed

    services.AddDbContext<AppDbContext>(options => {
        options.UseInMemoryDatabase("market-api-in-memory");
    });

    services.AddScoped<ICategoryRepository, CategoryRepository>();
    services.AddScoped<ICategoryService, CategoryService>();
}


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    // Routing is added from your version:
    app.UseRouting();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}
© www.soinside.com 2019 - 2024. All rights reserved.