The idea is that with these ItemController methods I should be able to:
- Get the items by barcode when hitting "item/query?barcode={barcode}"
- Get the items by discount when hitting "item/query?discount={discount}"
- Get the items by name when hitting "item/query?name={name}"
- Get the items by category when hitting "item/query?category={category}"
And this is my code for actions under the GET verb:
[HttpGet("query/{barcode:int}")]
public async Task<IActionResult> GetByBarcode(int barcode)
{
var item = ...
return Ok(item);
}
[HttpGet("query/{discount:int}")]
public async Task<IActionResult> GetByDiscount(int discount)
{
var items = ...
return Ok(items);
}
[HttpGet("query/{name}")]
public async Task<IActionResult> GetByName(string name)
{
var items = ...
return Ok(items);
}
[HttpGet("query/{category}")]
public async Task<IActionResult> GetByCategory(string category)
{
var items = ...
return Ok(items);
}
The problem is that I keep getting 405 Method Not Allowed when I try to access to any of those actions. I don't know if it's a matter of ambiguity between the methods, can you help me out?
Edit:
Header of ItemController.cs:
using InventoryWebApi.DataAccess;
using InventoryWebApi.DTO;
using InventoryWebApi.Models;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace InventoryWebApi.Controllers
{
[ApiController]
[Route("[controller]")]
public class ItemController : ControllerBase
{
private readonly IRepository repository;
public ItemController(IRepository repository)
...
CodePudding user response:
you are using routing a wrong way.
Your code will not be even run, your actions shoud be
[HttpGet("query/getbybarcode/{barcode:int})]
public async Task<IActionResult> GetByBarcode(int barcode)
[HttpGet("query/getbydiscount/{discount:int}")]
public async Task<IActionResult> GetByDiscount(int discount)
For this routes you have to use this urls
.../item/query/getbybarcode/{barcode}
..../item/query/getbydiscount/{discount}
if you still want to create url your way you will have to change attribute routing
[HttpGet("query/getbybarcode)]
public async Task<IActionResult> GetByBarcode(int barcode)
[HttpGet("query/getbydiscount")]
public async Task<IActionResult> GetByDiscount(int discount)
and your url should be
.../item/query/getbydiscount?discount={discount}"
..../item/query/getbybarcode?barcode={barcode}"
Update
If you still need to use all your urls for your student project , then the only way is to use one action for all your urls
[HttpGet("query")]
public async Task<IActionResult> Get(int? barcode, int? discount,
string name, string category )
{
if (barcode != null) ...
else if (discount!=null) ...
var item = ...
return Ok(item);
}