List of Guids not Model Binding Asp.Net Core
我正在使用aurelia-fetch-client将一个Guid数组发送到ASP.NET Core Web应用程序,但是在服务器端,模型绑定程序不会接收它,并且
我更改了我的控制器方法的签名,以接受字符串列表,以防万一GUID格式有问题,但还是同样的问题。
JS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | var body = {notificationIds : this.notifications.map(x => x.notificationId) }; console.log("Dismissing All notifications"); await this.httpClient.fetch('http://localhost:5000/api/notifications/clear', { method: 'POST', body: json(body), headers: { 'Authorization': `Bearer ${localStorage.getItem('access_token')}`, 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-Requested-With': 'Fetch' }, mode: 'cors' }).then(response => { if(response.status == 204){ //Success! Remove Notifications from VM } else{ console.log(response.status) } }) |
控制器方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | // POST: api/Notifications [HttpPost] [Route("clear")] [ProducesResponseType((int)HttpStatusCode.NoContent)] [ProducesResponseType((int)HttpStatusCode.BadRequest)] public async Task<IActionResult> Post([FromBody]List<string> notificationIds) { if (notificationIds.IsNullOrEmpty()) { return BadRequest("No notifications requested to be cleared"); } var name = User.Claims.ElementAt(1); await _notificationRepository.Acknowledge(notificationIds, name.Value); return NoContent(); } |
有趣的是,Chrome(V62)没有显示任何内容。
但Fiddler确实
这里的问题是您没有发送GUID列表,而是要发送具有包含GUID列表属性的对象。创建并使用视图模型(如peinearydevelopment所述),或者接受引用json对象的
1 2 3 4 | public async Task<IActionResult> Post([FromBody] dynamic json) { var notificationIds = json.notifcationIds; ... |
您从JavaScript传递的对象的形状不同于您告诉ASP.NET框架所期望的对象的形状。
有两种方法可以解决此问题:
选项1:
在您的JavaScript中,将您的正文更改为
选项2:
在c#中创建一个对象,该对象反映您从JavaScript传递的内容。
1 2 3 4 5 6 7 | namespace Foo { public class Bar { public List<string> NotificationIds { get; set; } } } |
,然后将您的控制器方法更新为以下内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | // POST: api/Notifications [HttpPost] [Route("clear")] [ProducesResponseType((int)HttpStatusCode.NoContent)] [ProducesResponseType((int)HttpStatusCode.BadRequest)] public async Task<IActionResult> Post([FromBody]Bar bar) { if (bar.NotificationIds.IsNullOrEmpty()) { return BadRequest("No notifications requested to be cleared"); } var name = User.Claims.ElementAt(1); await _notificationRepository.Acknowledge(bar.NotificationIds, name.Value); return NoContent(); } |