简体   繁体   English

无效的ModelState,发送给C#Web API控制器的JSON数组的HTTP 400错误请求

[英]Invalid ModelState, HTTP 400 Bad Request for JSON Array Sent to C# Web API Controller

In a C# Web API, I am trying to accept a POST request that contains a JSON array. 在C#Web API中,我试图接受包含JSON数组的POST请求。 I want to deserialize the JSON array to a LIST or ILIST of RegisterBindingModel class objects. 我想将JSON数组反序列ILIST RegisterBindingModel类对象的LISTILIST Then, in the controller actions, I will iterate over the list and perform the desired action. 然后,在控制器动作中,我将遍历列表并执行所需的动作。

I am using essentially the stock ASP.NET 5 Web Application template in Visual Studio 2015. I have added a RegisterList method on the Account controller. 我基本上在Visual Studio 2015中使用库存ASP.NET 5 Web应用程序模板。我在Account控制器上添加了RegisterList方法。

Separately, I have created a Web client in a C# console application. 另外,我在C#控制台应用程序中创建了一个Web客户端。 The client sends a POST request that contains a JSON array. 客户端发送包含JSON数组的POST请求。

The response I get is always 400 - Bad Request. 我得到的响应始终是400-错误请求。

Am I supposed to deserialize the JSON array to an ILIST or LIST in the RegisterList method signature? 我是否应该在RegisterList方法签名中将JSON数组反序列化为ILIST或LIST? I've tried to use JsonConverter.DeserializeObject , but IntelliSenese says that the type name DeserializeObject does not exist in type JsonConverter . 我尝试使用JsonConverter.DeserializeObject ,但是IntelliSenese说the type name DeserializeObject does not exist in type JsonConverter

The API documentation that generates with the Visual Studio template indicates that the client's JSON array is formatted correctly. 使用Visual Studio模板生成的API文档表明客户端的JSON数组格式正确。

The following is the code for the RegisterList method: 以下是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();
    }

The following is the code for the client: 以下是客户端的代码:

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 already encodes to JSON, so skip the JsonConvert.SerializeObject and just HttpClient.PostAsJsonAsync已经编码为JSON,因此跳过JsonConvert.SerializeObject并仅

HttpResponseMessage response = await client.PostAsJsonAsync("api/Account/RegisterList", 
                                                            registrations);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM