2016-07-25 5 views
0

C# 웹 API에서 JSON 배열이 포함 된 POST 요청을 수락하려고합니다. JSON 배열을 LIST 또는 ILISTRegisterBindingModel 클래스 객체로 deserialize하고 싶습니다. 그런 다음 컨트롤러 동작에서 목록을 반복하고 원하는 작업을 수행합니다.유효하지 않은 ModelState, HTTP 400 잘못된 JSON 배열 요청 (C# Web API 컨트롤러에 전송)

Visual Studio 2015에서 ASP.NET 5 Web Application 템플릿을 기본적으로 사용하고 있습니다. Account 컨트롤러에 RegisterList 메서드를 추가했습니다.

별도로 C# 콘솔 응용 프로그램에서 웹 클라이언트를 만들었습니다. 클라이언트는 JSON 배열이 포함 된 POST 요청을 보냅니다.

내가받는 응답은 항상 400 - 잘못된 요청입니다.

RegisterList 메서드 서명의 ILIST 또는 LIST로 JSON 배열을 deserialize해야합니까? 나는 JsonConverter.DeserializeObject을 사용하려했지만 IntelliSenese는 그 the type name DeserializeObject does not exist in type JsonConverter라고 말합니다.

Visual Studio 템플릿을 사용하여 생성되는 API 문서는 클라이언트의 JSON 배열이 올바르게 포맷되었음을 나타냅니다.

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

다음은 클라이언트의 코드입니다 : 다음

RegisterList 메서드에 대한 코드입니다

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 = "[email protected]", Password = "Secrets1!", ConfirmPassword = "Secrets1!" }, new Registration { Email = "[email protected]", Password = "Secrets1!", ConfirmPassword = "Secrets1!" }, new Registration { Email = "[email protected]", Password = "Secrets1!", ConfirmPassword = "Secrets1!" }, new Registration { Email = "[email protected]", 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(); 
     } 
    } 
} 
} 

답변

0

HttpClient.PostAsJsonAsync 이미 JSON으로 인코딩 때문에 JsonConvert.SerializeObject 그냥

를 건너
HttpResponseMessage response = await client.PostAsJsonAsync("api/Account/RegisterList", 
                  registrations); 
+0

당신이 옳습니다. 솔루션이 완벽하게 작동했습니다. 감사합니다. –