【问题标题】:Invalid ModelState, HTTP 400 Bad Request for JSON Array Sent to C# Web API Controller无效的 ModelState,发送到 C# Web API 控制器的 JSON 数组的 HTTP 400 错误请求
【发布时间】:2016-11-28 05:55:49
【问题描述】:

在 C# Web API 中,我试图接受包含 JSON 数组的 POST 请求。我想将 JSON 数组反序列化为 LISTILISTRegisterBindingModel 类对象。然后,在控制器动作中,我将遍历列表并执行所需的动作。

我基本上在 Visual Studio 2015 中使用库存的 ASP.NET 5 Web 应用程序模板。我在 Account 控制器上添加了一个 RegisterList 方法。

另外,我在 C# 控制台应用程序中创建了一个 Web 客户端。客户端发送一个包含 JSON 数组的 POST 请求。

我得到的响应总是 400 - Bad Request。

我是否应该将 JSON 数组反序列化为 RegisterList 方法签名中的 ILIST 或 LIST?我尝试使用JsonConverter.DeserializeObject,但IntelliSensee 说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();
        }
    }
}
}

【问题讨论】:

    标签: c# json controller asp.net-web-api2 modelstate


    【解决方案1】:

    HttpClient.PostAsJsonAsync 已经编码为 JSON,因此请跳过 JsonConvert.SerializeObject 直接

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

    【讨论】:

    • 你完全正确。您的解决方案非常有效,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2021-10-12
    • 2015-02-23
    • 1970-01-01
    • 2015-02-25
    • 2014-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多