非模型绑定的 Guids 列表 Asp.Net Core

List of Guids not Model Binding Asp.Net Core

我正在使用 aurelia-fetch-client 向 ASP.NET Core Web 应用程序发送一个 Guid 数组,但是在服务器端,模型绑定器没有接收它并且 notificationIdsnull。但是,当我通过 Swagger 或 CURL 发出请求时,它绑定得很好。

我更改了我的控制器方法的签名以接受字符串列表,以防 GUID 格式出现问题,但同样的问题。

JS

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)
            }
        })

控制器方法

// 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 会

您从 JavaScript 传递的 object 的形状与您告诉 ASP.NET 框架期望的 object 的形状不同。

您可以通过两种方式解决此问题:

选项 1: 在您的 JavaScript 中,将 body 更改为 var body = this.notifications.map(x => x.notificationId);

选项 2: 在 c# 中创建一个 object 来反映您从 JavaScript.

传递的内容
namespace Foo
{
  public class Bar
  {
    public List<string> NotificationIds { get; set; }
  }
}

然后将您的控制器方法更新为以下内容:

// 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();
}

这里的问题是您没有发送 GUID 列表,您发送的是 属性 包含 GUID 列表的对象。创建并使用视图模型(如 peinearydevelopment 所述)或接受引用 json 对象的 dynamic 参数。

public async Task<IActionResult> Post([FromBody] dynamic json)
{
    var notificationIds = json.notifcationIds;
    ...