Asp.net core - How to create a controller action with optional parameters

In this post I show you how to use optional parameters in asp.net core. It is actually quite simple as it works just the same as normal optional parameters for methods. Below I have created the endpoint /api/test/TryItOut with 3 optional parameters. A string (""), an integer (0) and a date (null):

[Route("api/Test")]
[ApiController]
public class TestController : ControllerBase
{
    [HttpGet("TryItOut")]
    public void Try(string s = "", int i = 0, DateTime? date = null)
    {
        //s is "",
        //i is 0
        //Date is null
    }
}

In the above you can specify all, some or none of the parameters. If you do not provide one of the parameters it will be set to what you have specified as the optional value ("", 0, null). I have used a nullable DateTime as these values have to be compile constants, which DateTime.MinValue is not.

If you have many optional parameters, or just many parameters the above might start to look cluttered. As an alternative you can make your controller action take an object like below:

[Route("api/Test")]
[ApiController]
public class TestController : ControllerBase
{
    [HttpGet("TryItOut")]
    public void Try([FromQuery]SomeObject someObject)
    {
        //someObject.S is "",
        //someObject.I is 0
        //someObject.Date is null
    }
}

public class SomeObject
{
    public string S { get; set; } = "";
    public int I { get; set; } = 0;
    public DateTime? Date { get; set; } = null;
}

This will have the exact same effect as the previous example when you use the FromUri annotation. You do not have to set the values in the object, for example the String would normally default to null, I have only set them in the above to be more explicit in this post.

Let me know in the comments if this post helped you :) or if you have a better way of achieving this.