2016-10-22 11 views
0

ASP.NET 코어 응용 프로그램에서 MVC 컨트롤러에 대한 간단한 POST 요청을 클라이언트에서 시도하려고합니다. 문제는 비록 내가 아약스 호출을 제대로 (내가 생각하는) 설정했습니다, 페이로드 항상 양식 URL을 인코딩으로 제출하고 서버에 내 모델은 null을 끝납니다. 여기 내 설정은 다음과 같습니다ASP.NET 코어 POST에서 MVC

컨트롤러 활동 정의 :

[HttpPost] 
 
public async Task<EmailResponse> SendEmail([FromBody] EmailModel model) 
 
{ 
 
EmailResponse response = new EmailResponse(); 
 

 
... 
 

 
return response; 
 
}

모델 :

public class EmailModel 
 
{ 
 
[JsonProperty("fistName")] 
 
public string FirstName { get; set; } 
 
[JsonProperty("lastName")] 
 
public string LastName { get; set; } 
 
[JsonProperty("email")] 
 
public string Email { get; set; } 
 
[JsonProperty("company")] 
 
public string Company { get; set; } 
 
[JsonProperty("message")] 
 
public string Message { get; set; } 
 
}

클라이언트 아약스 전화 :

POST /Home/SendEmail HTTP/1.1 
 
Host: localhost:5000 
 
Connection: keep-alive 
 
Content-Length: 77 
 
Pragma: no-cache 
 
Cache-Control: no-cache 
 
Accept: */* 
 
Origin: http://localhost:5000 
 
X-Requested-With: XMLHttpRequest 
 
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 
 
Content-Type: application/json; charset=UTF-8 
 
Referer: http://localhost:5000/ 
 
Accept-Encoding: gzip, deflate 
 
Accept-Language: en-US,en;q=0.8 
 
Cookie: _ga=GA1.1.116706601.1460641478 
 

 
firstName=Joe&lastName=Doe&email=test%40test.com&company=Acme%2C+Inc&message=

주의 요청의 끝 부분에있는 페이로드 : 여기

$.ajax({ 
 
    type: "POST", 
 
    url: "/Home/SendEmail", 
 
    contentType: 'application/json; charset=utf-8', 
 
    data: model 
 
}).done(function (result) { 
 
    ... 
 
}).error(function(error) { 
 
    ... 
 
});

내 요청입니다. 일반 JS 객체를 전달하고 contentType을 application/json으로 지정하더라도 JSON 형식이 아닙니다. 왜 내 모델이 서버에서 항상 null인지 추측하고 있습니다.

저는 지금이 문제에 대해 몇 시간 꼼짝 않고보고 있었으므로 문제가있는 곳을 볼 수 없습니다. 모든 입력은 크게 감사드립니다.

감사합니다.

답변

1

모델이 json으로 직렬화되지 않았습니다. 객체는 기본 미디어 유형 (키 값 쌍)으로 serialize됩니다.이를 "application/x-www-form-encoded"라고합니다.

시도는 우리가 더 가까워지고있는 JSON

$.ajax({ 
    type: "POST", 
    url: "/Home/SendEmail", 
    contentType: 'application/json; charset=utf-8', 
    data: JSON.stringify(model) //notice the JSON.stringify call 
}).done(function (result) { 
    ... 
}).error(function(error) { 
    ... 
}); 
+0

확인을 시행합니다. 이제 모델이 나오지만 모든 속성은 null입니다. 나는 들판의 정의를 확인해야만 할 것 같아. 각 필드에 JsonProperty를 설정했지만 거기에 뭔가가 누락되었을 수 있습니다. 나는 모델의 정의를 포함하도록 나의 질문을 업데이트했다 – dpdragnev

+0

고마워. 이것은 그것을했다. – dpdragnev

+0

AFAIK asp.net 코어는 camelCase의 이름 지정과 호환되므로 JsonProperty 특성을 제거 할 수 있습니다. https://wildermuth.com/2016/06/27/Converting-ASP-NET-Core-1-0-RC2-to-RTM-Bits – Operatorius

관련 문제