1

Read all the advantages of using ApiControllerAttribute, however, if we want to have optional parameter while using this attribute for query parameter, it doesn't work. It still validates all parameters as mandatory. Any idea how to make it optional?

[ApiController]    
public class testController: ControllerBase
{
    [HttpGet("employees/{id?}")]
    public List<Employees> GetAll(int? id)
    {
        // gets all employees or by id
    }
}

When this code is executed, it expects id all the time. It does not run without this parameter.

EDIT: it doesnt work even when default value of id is passed.

genericuser
  • 1,430
  • 4
  • 22
  • 40
  • 1
    Add a default value `[HttpGet("employees/{id?}")] public List GetAll(int? id = null)` – Nkosi Aug 07 '19 at 23:41
  • Well, tried that, it still says "The value 'null' is not valid" 400 error. This is because ApiController does the validation. If I remove it, it works fine. I just want to know, how to make it work with ApiController attribute. – genericuser Aug 08 '19 at 01:33
  • Maybe docs here might help in understanding ApiController https://learn.microsoft.com/en-us/aspnet/core/web-api/ – Nkosi Aug 08 '19 at 01:41
  • What is your .net core version? I made a test with `netcoreapp2.2`, it works correctly with `[HttpGet("employees/{id?}")]`. Share us a mini demo which could reproduce your issue. – Edward Aug 08 '19 at 01:59
  • .net core version 2.1.603. I read that documentation, however, it didnt work thats why this question. Could it be the version? – genericuser Aug 08 '19 at 02:08
  • Share us a mini demo, it works with built-in template .net core 2.1. – Edward Aug 08 '19 at 06:01
  • 1
    it turned out that this was a swagger issues, rather than the .net core web api issue - https://stackoverflow.com/questions/46764769/swagger-web-api-optional-query-parameters – genericuser Aug 08 '19 at 13:45

1 Answers1

0

Give a route to your ApiController

[Route("api/[controller]")]
[ApiController]
public class ReposController : ControllerBase
{
   //GetAll api/repos
   public IEnumerable<Employees> Getall()
   {
   //Your code
   }

    //GET api/repos/id
    [HttpGet("{id}", Name = "Getid")]
    public Employees GetEmployees(int id)
    {
    //Your code
    }

}

Hope it helps

Shervin Ivari
  • 1,759
  • 5
  • 20
  • 28