404 not found when trying to run Api Controller function from ASP.NET core 5 web app
Asked Answered
B

1

5

I am trying to create an API controller in my ASP.NET core 5 Razor Pages web application.

I have created the Api Controller inside a folder named Api in Visual studio.

Then when I try to run the following url to test that the api controller works, I get a 404 not found:

https://localhost:345345/api/saveimage

What am I missing?

Api Controller (SaveImageController.cs):

[Route("api/[controller]")]
[ApiController]
public class saveImageController : ControllerBase
{
    [HttpGet]
    public IEnumerable<string> Get()
    {
        return new string[] { "test", "test2" };
    }
}
Branscum answered 11/7, 2021 at 13:34 Comment(0)
S
9

Even though using folder "Api" for your controller will work, it is normal to keep controllers inside a folder called "Controllers".

Please note that Razor pages are using folder based routing, the same does not apply to controllers.

In Startup#ConfigureServices, make sure you have this:

services.AddControllers();

In Startup#Configure, make sure you have this:

app.UseEndpoints(endpoints =>
{
    endpoints.MapRazorPages();
    endpoints.MapControllers();
});
Sholeen answered 11/7, 2021 at 14:20 Comment(1)
Thank you! for some reason all the guides I checked failed to mention thisBranscum

© 2022 - 2024 — McMap. All rights reserved.