How to pass null value to nullable types in WebAPI

Viewed 4375

I have a function as below:

        [HttpGet]
        [Route("Departments/{departmentid}/employeeByDeptId")]
        [ResponseType(responseType: typeof(IList<Employee>))]
        public HttpResponseMessage GetDetailsByDeptId(int departmentId, DateTime? sinceDate)
        {
            if (!ModelState.IsValid)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }

            var detailInfo = _employeeManager.GetDetailInfo(departmentId, sinceDate ?? _sinceDate);

            return CreateHttpResponseMessage(detailInfo);

        }

I have made sinceDate as Nullable type in declaration so that if null value is passed it takes the date which is there in '_sinceDate' variable declared locally. Now how can I pass null value to sinceDate parameter while making an API call.

When I pass below url: http://localhost:26754/v1/EmployeeMgnt/Departments/4/employeeByDeptId?sinceDate=2020-03-03

I get the desired result. Now I want to pass sinceDate as null. I tried http://localhost:26754/v1/EmployeeMgnt/Departments/4/employeeByDeptId?sinceDate=null http://localhost:26754/v1/EmployeeMgnt/Departments/4/employeeByDeptId?sinceDate isnull

All gave bad request error. Please tell how can I assign null value to sinceDate in API call?

2 Answers

Simply add parameterName = null in your route parameter.

public HttpResponseMessage GetDetailsByDeptId(int departmentId, DateTime? sinceDate = null){
}

Then in your request, you could just exclude that parameter and access with;

http://localhost:26754/v1/EmployeeMgnt/Departments/4/employeeByDeptId

Another option is add an overload. Have 2 function names receive different parameters.

public HttpResponseMessage GetDetailsByDeptId(int departmentId, DateTime sinceDate){
}

public HttpResponseMessage GetDetailsByDeptId(int departmentId){
}
Related