无效的 ModelState,JSON 数组发送到 C# Web API 控制器的 HTTP 400 错误请求
Invalid ModelState, HTTP 400 Bad Request for JSON Array Sent to C# Web API Controller
在 C# Web API 中,我试图接受包含 JSON 数组的 POST
请求。我想将 JSON 数组反序列化为 LIST
或 ILIST
的 RegisterBindingModel
class 对象。然后,在控制器操作中,我将遍历列表并执行所需的操作。
我基本上使用 Visual Studio 2015 中的股票 ASP.NET 5 Web 应用程序模板。我在 Account
控制器上添加了一个 RegisterList
方法。
另外,我在 C# 控制台应用程序中创建了一个 Web 客户端。客户端发送一个 POST 请求,其中包含一个 JSON 数组。
我得到的响应总是 400 - 错误请求。
我是否应该将 JSON 数组反序列化为 RegisterList
方法签名中的 ILIST 或 LIST?我试过使用 JsonConverter.DeserializeObject
,但 IntelliSenese 说 the type name DeserializeObject does not exist in type JsonConverter
.
使用 Visual Studio 模板生成的 API 文档表明客户端的 JSON 数组格式正确。
下面是RegisterList
方法的代码:
// POST api/Account/RegisterList
[AllowAnonymous]
[Route("RegisterList")]
public async Task<IHttpActionResult> RegisterList(List<RegisterBindingModel> modelList)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
foreach (RegisterBindingModel model in modelList)
{
var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
}
return Ok();
}
客户端代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using Web_Client_Register_Account;
using Newtonsoft.Json;
namespace Web_Client_Register_Account
{
class Program
{
static void Main(string[] args)
{
RunAsync().Wait();
}
static async Task RunAsync()
{
using (var client = new HttpClient())
{
Console.WriteLine("Hit any key");
Console.ReadLine();
client.BaseAddress = new Uri("http://localhost:9000/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var registrations = new List<Registration> { new Registration { Email = "orc@coast2coast.net", Password = "Secrets1!", ConfirmPassword = "Secrets1!" }, new Registration { Email = "gargoyle@coast2coast.net", Password = "Secrets1!", ConfirmPassword = "Secrets1!" }, new Registration { Email = "elf@coast2coast.net", Password = "Secrets1!", ConfirmPassword = "Secrets1!" }, new Registration { Email = "ranger@coast2coast.net", Password = "Secrets1!", ConfirmPassword = "Secrets1!" } };
//HTTP Post - A JSON List in a Single POST
var registration_manifest = JsonConvert.SerializeObject(registrations);
Console.ReadLine();
HttpResponseMessage response = await client.PostAsJsonAsync("api/Account/RegisterList", registration_manifest);
if (response.IsSuccessStatusCode)
{
Uri registrantUrl = response.Headers.Location;
Console.WriteLine(registrantUrl);
Console.ReadLine();
}
Console.WriteLine(response);
Console.ReadLine();
}
}
}
}
HttpClient.PostAsJsonAsync
已经编码为 JSON,因此跳过 JsonConvert.SerializeObject
,只编码
HttpResponseMessage response = await client.PostAsJsonAsync("api/Account/RegisterList",
registrations);
在 C# Web API 中,我试图接受包含 JSON 数组的 POST
请求。我想将 JSON 数组反序列化为 LIST
或 ILIST
的 RegisterBindingModel
class 对象。然后,在控制器操作中,我将遍历列表并执行所需的操作。
我基本上使用 Visual Studio 2015 中的股票 ASP.NET 5 Web 应用程序模板。我在 Account
控制器上添加了一个 RegisterList
方法。
另外,我在 C# 控制台应用程序中创建了一个 Web 客户端。客户端发送一个 POST 请求,其中包含一个 JSON 数组。
我得到的响应总是 400 - 错误请求。
我是否应该将 JSON 数组反序列化为 RegisterList
方法签名中的 ILIST 或 LIST?我试过使用 JsonConverter.DeserializeObject
,但 IntelliSenese 说 the type name DeserializeObject does not exist in type JsonConverter
.
使用 Visual Studio 模板生成的 API 文档表明客户端的 JSON 数组格式正确。
下面是RegisterList
方法的代码:
// POST api/Account/RegisterList
[AllowAnonymous]
[Route("RegisterList")]
public async Task<IHttpActionResult> RegisterList(List<RegisterBindingModel> modelList)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
foreach (RegisterBindingModel model in modelList)
{
var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
}
return Ok();
}
客户端代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using Web_Client_Register_Account;
using Newtonsoft.Json;
namespace Web_Client_Register_Account
{
class Program
{
static void Main(string[] args)
{
RunAsync().Wait();
}
static async Task RunAsync()
{
using (var client = new HttpClient())
{
Console.WriteLine("Hit any key");
Console.ReadLine();
client.BaseAddress = new Uri("http://localhost:9000/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var registrations = new List<Registration> { new Registration { Email = "orc@coast2coast.net", Password = "Secrets1!", ConfirmPassword = "Secrets1!" }, new Registration { Email = "gargoyle@coast2coast.net", Password = "Secrets1!", ConfirmPassword = "Secrets1!" }, new Registration { Email = "elf@coast2coast.net", Password = "Secrets1!", ConfirmPassword = "Secrets1!" }, new Registration { Email = "ranger@coast2coast.net", Password = "Secrets1!", ConfirmPassword = "Secrets1!" } };
//HTTP Post - A JSON List in a Single POST
var registration_manifest = JsonConvert.SerializeObject(registrations);
Console.ReadLine();
HttpResponseMessage response = await client.PostAsJsonAsync("api/Account/RegisterList", registration_manifest);
if (response.IsSuccessStatusCode)
{
Uri registrantUrl = response.Headers.Location;
Console.WriteLine(registrantUrl);
Console.ReadLine();
}
Console.WriteLine(response);
Console.ReadLine();
}
}
}
}
HttpClient.PostAsJsonAsync
已经编码为 JSON,因此跳过 JsonConvert.SerializeObject
,只编码
HttpResponseMessage response = await client.PostAsJsonAsync("api/Account/RegisterList",
registrations);