【问题标题】:Using [FromQuery] with a complex object将 [FromQuery] 与复杂对象一起使用
【发布时间】:2021-02-23 21:28:45
【问题描述】:

我在传递查询字符串时向我的 API 端点发送请求时遇到参数未绑定的问题,如果我展平提交,则参数绑定,但这不是我想要的解决方案。我无法提供在第三方控件处理请求时发送请求的客户端代码。

我提供了一个与请求一起发送的查询字符串示例,可以在开发人员工具中看到,但是,Person 和 Property 返回为 null。有没有人有任何建议,特别是我可以做的服务器端更改来绑定这个复杂的对象?谢谢。

public class Submission {
    public Person Person {get; set; }
    public Property Property { get; set; }
}

public class Person {
   public int Age { get; set; }
}

public class Property {
   public string Address { get; set; }
}

Query string parameters

'Person[Age]': 18
'Property[Address]': test

 [HttpGet("action")]
 public async Task<IActionResult> Submit([FromQuery] Submission model)
 {

 }

【问题讨论】:

  • 在查询字符串中尝试Person.Age

标签: c# .net asp.net-mvc asp.net-core .net-core


【解决方案1】:

在这种情况下,您要调用的 URL 是:

https://localhost:.../.../action?Person.Age=18&Property.Address=test

【讨论】:

    【解决方案2】:

    改变你的行动:

    [HttpGet("Submit")]
     public async Task<IActionResult> Submit([FromQuery] Submission model)
     {
    
     }
    

    为你的提交模型试试这个

    public class Submission {
        public int Age {
        
           set{ 
               if (Person=null Person= new Person();
               Person.Age=value;
             } 
    }
        public string Address ... code like above;
        public Person Person {get; set; }
        public Property Property { get; set; }
    }
    
    or you can create
    
    public class SubmissionModel:Submission
    {
    public int Age {
          
           set{ 
               if (Person=null) Person= new Person();
               Person.Age=value;
             } 
    }
    }
    in this case you action will be
    [HttpGet("Submit")]
     public async Task<IActionResult> Submit([FromQuery] SubmissionModel subModel)
     {
             var model = subModel as Submission;
               ...............
     }
    

    在这种情况下,您必须调用此 URL:

    https://localhost:.../.../submit?Age=18&Address=myaddress

    【讨论】:

    • 如原帖中所述,展平对象确实有效,但是,我的示例是简化版本,我不希望展平我的多嵌套类。不过感谢您的建议!
    猜你喜欢
    • 2019-08-26
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 2018-10-24
    • 2021-07-12
    相关资源
    最近更新 更多