如何将空值传递给WebAPI中的可为空的类型

问题描述 投票:0回答:1

我具有以下功能:

        [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);

        }

我在声明中将sinceDate作为Nullable类型,因此,如果传递了null值,它将采用本地声明的'_sinceDate'变量中存在的日期。现在,如何在进行API调用时将null值传递给sinceDate参数。

当我在网址下方传递时:http://localhost:26754/v1/EmployeeMgnt/Departments/4/employeeByDeptId?sinceDate=2020-03-03

我得到了期望的结果。现在,我想将sinceDate传递为null。我试过了http://localhost:26754/v1/EmployeeMgnt/Departments/4/employeeByDeptId?sinceDate=nullhttp://localhost:26754/v1/EmployeeMgnt/Departments/4/employeeByDeptId?sinceDate无效

所有人都给出了错误的请求错误。请告诉我如何在API调用中将null值分配给sinceDate?

c# asp.net asp.net-mvc nullable webapi
1个回答
0
投票
只需在路由参数中添加parameterName = null

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

然后在您的请求中,您可以仅排除该参数并使用进行访问;

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


另一个选择是添加重载。有2个函数名称接收不同的参数。

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

© www.soinside.com 2019 - 2024. All rights reserved.