Skip to main content
 首页 » 编程设计

c#之ASP.NET WebAPI HttpGet 操作之查询字符串后模型为空

2024年02月06日18emanlee

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

Action :

    [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 MVC 还是 Web API?从您从 Controller 操作而不是 ActionResult 返回员工列表这一事实,我可以看出它是 Web API。如果是这样,您可以将 [FromUri] 属性应用于模型:

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