0

I try to start asp.net core web api routing attribute as default route but when I access routing with parameter, I could not get any response

[Route("api/[controller]")]
[ApiController]
public class WarehousesController : ControllerBase
{
    private readonly ApplicationDbContext _context;

    public WarehousesController(ApplicationDbContext context)
    {
        _context = context;
    }

    //http://localhost:2394/api/Warehouses/Project/1 (Not working)
    [HttpGet("Project/{projectId}")]
    public async Task<IActionResult> GetWarehouseByProjectId([FromRoute] int projectId)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var warehouse = await _context.warehouses.Include(x => x.Projects).Where(y => y.Projects.FirstOrDefault().ProjectId == projectId).ToListAsync();

        if (warehouse == null)
        {
            return NotFound();
        }

        return Ok(warehouse);
    }

}
7
  • What do you mean not working?Do you add a breakpoint to check whether you get the projectId in action? Commented May 15, 2019 at 3:31
  • return url not found but I don't include {projectId} and access url localhost:2394/api/Warehouses/Project. It's ok Commented May 15, 2019 at 4:54
  • @vannak by default the id will be zero (0) , which according to your code, may return a null warehouse and cause a NotFound() result to be returned. Commented May 15, 2019 at 5:08
  • It works well when I try your code.Could you show your startup routing?Do you have problem in a new project? Commented May 15, 2019 at 5:23
  • I test this url with postman. return not found url. It meas routing attribute with parameter not invoke to method Commented May 15, 2019 at 6:08

1 Answer 1

2

Try with this one .This works fine for me

[HttpGet("Project/{projectId}")]
public async Task<IActionResult> GetWarehouseByProjectId([FromRoute] int projectId)
{
  if (!ModelState.IsValid)
    {
        return BadRequest("Invalid state");
    }

    var warehouse =await _context.warehouses.FindAsync(projectId);
    
    if (warehouse == null)
    {
        return NotFound("not found");
    }

    return Ok(warehouse);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.