ASP.NET WebAPI HttpGet Action-查询字符串后的模型为null

本文关键字:模型 null 字符串 查询 NET WebAPI HttpGet Action- ASP | 更新日期: 2023-09-27 18:26:33

MVC操作未反序列化下面的查询字符串。该操作可以命中,但在该操作中searchModel的值为空。

https://test.api.domain.com:9090/mont/contact/searchemployee?lastname=Smith

编辑:简化模型

型号

public class EmployeeSearchModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

操作:

    [HttpGet]
    public List<Employee> SearchEmployee(EmployeeSearchModel searchModel)
    {
        List<Employee> employees = new List<Employee>();
        try
        {
            if (searchModel != null)
            {
                //some logic
            }
            else
            {
                //dirty feedback for testing - this is what the action returns
                employees.Add(new Employee { FirstName = "searchModel was null" });
            }
        }
        catch (Exception e) { WriteFileLog(_logPath, e.ToString()); }
        return employees;
    }

ASP.NET WebAPI HttpGet Action-查询字符串后的模型为null

是ASP.NET MVC还是Web API?从您从控制器操作而不是ActionResult返回员工列表的事实中,我可以看出它是Web API。如果是,您可以将[FromUri]属性应用于模型:

public List<Employee> SearchEmployee([FromUri]EmployeeSearchModel searchModel)