2017-11-16 7 views
0

Json REST API를 호출해야하는 .NET Core 웹 응용 프로그램 개발.HttpClient.PostAsync()의 결과를 가져 오지 못함

호출자 :

 using (HttpClient client = new HttpClient()) 
     { 
      client.DefaultRequestHeaders.Accept.Clear(); 
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

      AuthorizationUser user = new AuthorizationUser { User = "<user>", Application = "<app>" }; 

      var content = new StringContent(JsonConvert.SerializeObject(user), Encoding.UTF8, "application/json"); 
      HttpResponseMessage response = await client.PostAsync(new Uri("http://localhost:8081/Roles"), content); 
      // ... 
     } 

호 출처 :

[AllowAnonymous] 
    [HttpPost] 
    public HttpResponseMessage Post(AuthorizationUser user) 
    { 
     try 
     { 
      user = FillRoles(user); 
      return Request.CreateResponse(HttpStatusCode.OK, user); 
     } 
     catch (System.Exception ex) 
     { 
      return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex); 
     } 
    } 

모델 (호출자와 피 호출자에서) 피 호출자의 브레이크 포인트에 도달 할 때

public class AuthorizationUser 
{ 

    public AuthorizationUser() // Added thanks to CodeFuller 
    { } 

    public AuthorizationUser(string user, string application) 
    { 
     User = user ?? throw new ArgumentNullException(nameof(user)); 
     Application = application ?? throw new ArgumentNullException(nameof(application)); 

    } 
    public string User { get; set; } 
    public string Application { get; set; } 
    public IEnumerable<string> Roles { get; set; } 
} 

user 접수 항상 null입니다. 동일한 결과 앞에 [FromBody][FromUri]을 추가하려고했습니다.

내가 뭘 잘못하고 있니?

답변

1

올바르게 입력 한 사용자가 UserApplication 필드가되지 않습니다.

모델 바인딩 중 오류가 발생했습니다. 문제는 다음과 같은 확인 진단하려면 :

  1. Post() 방법 ActionContext.ModelState.IsValid의 가치는 무엇인가. true 또는 false입니까?
  2. false 인 경우 디버거에서 ActionContext.ModelState.Values 콜렉션을 확인하십시오. 모델 바인딩 오류가 있어야합니다.
+0

팁 주셔서 감사합니다. 문제는 반으로 해결되었습니다. 수표 1은 거짓이었습니다. Checked 2. :'유형 AuthorizationUser에 사용할 생성자를 찾을 수 없습니다. 클래스에는 기본 생성자, 인수가있는 생성자 또는 JsonConstructor 속성으로 표시된 생성자가 있어야합니다. Path 'Headers', line 1, position 11.' –

+0

그래서 기본 생성자를 추가했습니다. (하나를 추가했지만'private'입니다.) 이제'user'는 null이 아니지만 그 값은 null이고'ModelState.IsValid'는 true입니다. –

+0

이제 ModelState.IsValid가 true입니까? – CodeFuller