6

I have set up a very simple ASP.NET Core 2.1 Web API project, and have created to following simple controller that fetches entites using EF Core.

The problem is that when trying to access the GetEntities method using Postman, the response is a 404 error. I used an HTTP GET method on the following URL.

https://localhost:44311/api/entities

The response body contains the message <pre>Cannot GET /api/entities</pre>.

Why is Postman receiving a 404 error for this route?

EntitiesController.cs

namespace MyProject.Controllers
{
    [Route("api/controller")]
    public class EntitiesController : Controller
    {
        private readonly ApplicationDbContext dbContext;

        public EntitiesController(ApplicationDbContext _dbContext)
        {
            this.dbContext = _dbContext;
        }

        [HttpGet]
        public IActionResult GetEntities()
        {
            var result = dbContext.Entities.ToListAsync();
            return Ok(result);
        }
    }
}

3 Answers 3

10

Why is Postman receiving a 404 error for this route?

The issue was the controller token [controller] was missing from the route template on the controller, causing the route to be hard-coded to api/controller.

That meant that when requesting api/entities it technically did not exist and thus 404 Not Found when requested.

Update the route template on the controller.

[Route("api/[controller]")]
public class EntitiesController : Controller {
    private readonly ApplicationDbContext dbContext;

    public EntitiesController(ApplicationDbContext _dbContext) {
        this.dbContext = _dbContext;
    }

    //GET api/entities
    [HttpGet]
    public async Task<IActionResult> GetEntities() {
        var result = await dbContext.Entities.ToListAsync();
        return Ok(result);
    }
}

Reference Routing to controller actions in ASP.NET Core : Token replacement in route templates ([controller], [action], [area])

Sign up to request clarification or add additional context in comments.

Comments

6

Your route is "api/controller", not "api/entities". You need to put square brackets around "controller" for the desired effect - "api/[controller]".

Comments

0

Makesure the controller file name and the class name is correct, it should be postfix with word"Controller" eg., UsersController.cs

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.