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

时间:2014-10-15 15:21:33

标签: c# asp.net-web-api model deserialization

下面的查询字符串未被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;
    }

1 个答案:

答案 0 :(得分:4)

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

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