kanika
kanika

Reputation: 102

How to pass null value to nullable types in WebAPI

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?

Upvotes: 2

Views: 12570

Answers (2)

carl-johan.blomqvist
carl-johan.blomqvist

Reputation: 541

For anyone reading this, as far as I can tell, the accepted answer doesn't work (in itself) anymore. See https://github.com/dotnet/aspnetcore/issues/6878#issuecomment-647830903 for more details and the 2 different alternative ways around it.

Upvotes: 1

Jerdine Sabio
Jerdine Sabio

Reputation: 6130

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){
}

Upvotes: 2

Related Questions