C# 模型绑定复杂 属性

C# Model binding complex property

在我的 REST API 中,我的模型绑定没有映射作为对象列表的 属性。它正确到达控制器,并显示所有属性,但它们是空的。

例如对于 POST 请求 {age: 202, setting: ["school"]} 我在响应中得到类似这样的内容:

Got param type=SearchStringDTO; param={"age":202,"setting":[]}

我希望它以这样的方式响应:

Got param type=SearchStringDTO; param={"age":202,"setting":["school":true, "hospital":false]}

如何引导它把设置参数解析成List<Setting>

这是控制器:

using System.Web.Http;
...
        [HttpPost]
        public HttpResponseMessage Index(SearchStringDTO param) {
            return ResponseMessage(this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Got param type= " + param.GetType() + "; param = " + JsonConvert.SerializeObject(param)));

        }

这是模型:

    public sealed class SearchStringDTO {
        public int age { get; set; }

        public List<Setting> setting { get; set; }
    }

这里是设置 class:

    public class Setting {
        public bool hospital { get; set; }
        public bool school { get; set; }
    }

我开始沿着这条路手动解析东西,但这是 JObject、JToken、JArray 东西的噩梦。

        [HttpPost]
        public IHttpActionResult Index(Newtonsoft.Json.Linq.JObject param) {
            return ResponseMessage(this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Got param type= " + param.GetType() + "; param = " + JsonConvert.SerializeObject(param)));
        }

也许我需要自定义绑定模型?我在试图弄清楚如何构建和使用一个时迷路了。

您的代码没有问题,但是您的 json 输入参数格式不正确。我测试了

[HttpPost]
public string Index( [FromBody] SearchStringDTO param)
{
return "Got param type= " + param.GetType()
 + "; param = " + JsonConvert.SerializeObject(param);
}

在邮递员中使用:

 {age: 202, setting: [{"school":false, "hospital":true},{"school":true, "hospital":false}]}

并得到输出:

Got param type= SearchStringDTO; param = {"age":202,"setting":[{"hospital":true,"school":false},{"hospital":false,"school":true}]}