Web API 매개 변수는 항상 null입니다.
아래 Ajax를 사용하여 아래 Post 메서드를 호출하면 파라미터가 항상 null인 이유는 무엇입니까?
public IEnumerable<string> Post([FromBody]string value)
{
return new string[] { "value1", "value2", value };
}
다음은 Ajax를 통한 Web API 메서드 호출입니다.
function SearchText() {
$("#txtSearch").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "api/search/",
data: "test",
dataType: "text",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
$.ajax({
url: '/api/search',
type: 'POST',
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
data: '=' + encodeURIComponent(request.term),
success: function (data) {
response(data.d);
},
error: function (result) {
alert('Error');
}
});
기본적으로 스칼라 타입의 파라미터는 1개뿐입니다.[FromBody]
Atribute 및 당신의 요구는application/x-www-form-urlencoded
POST payload는 다음과 같습니다.
=somevalue
표준 프로토콜과 달리 파라미터 이름이 누락되어 있습니다.값만 보냅니다.
Web API에서의 모델바인딩의 자세한 것은, 을 참조해 주세요.
하지만 물론 이런 해킹은 역겨운 일이다.뷰 모델을 사용해야 합니다.
public class MyViewModel
{
public string Value { get; set; }
}
그 다음, 그 다음,[FromBody]
속성:
public IEnumerable<string> Post(MyViewModel model)
{
return new string[] { "value1", "value2", model.Value };
}
다음으로 JSON 요구를 사용합니다.
$.ajax({
url: '/api/search',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ value: request.term }),
success: function (data) {
response(data.d);
},
error: function (result) {
alert('Error');
}
});
에는 단순한 타입을 사용할 수 없습니다.[FromBody]
JSON 콘텐츠유형의 Atribute를 지정합니다.Visual Studio의 기본값에는 본문 문자열이 있지만 이는 응용 프로그램/x-www-form-urlencoded 콘텐츠 유형에 대한 것입니다.
기본 모델 클래스에 문자열 값을 속성으로 지정하면 역직렬라이저가 작동합니다.
public class SimpleModel()
{
public string Value {get;set;}
}
public IEnumerable<string> Post([FromBody]SimpleModel model)
{
return new string[] { "value1", "value2", model.Value };
}
송신처의 JSON을 변경합니다.
{"Value":"test"}
web api 작업을 호출할 때마다 [from body] 매개 변수를 선택한 다음 매개 변수 접두사를 =와 함께 입력합니다.
public string GetActiveEvents([FromBody] string XMLRequestString) {
}
위의 웹 API 액션을 호출하다
URI
2.
사용자 에이전트: 피들러
Content-Type: application/x-www-form-urlencoded
호스트: localhost: 54702
콘텐츠 길이: 936
- 요청 본문은 =data입니다.
나는 이것이 명확한 아이디어를 주길 바란다.
저는 이것과 으로 아주 힘든 시간을 보냈습니다.NET Core Web API.따라서 누군가에게 시간을 절약해 주었으면 합니다.실제 문제는 단순했습니다. 올바른 유형으로 변환하지 않았습니다(Notice @Darins 답변에는 문자열이 아닌 VM이 사용됨).
템플릿의 기본 유형은 다음과 같습니다.string
스트링화된 JSON을 보내드리기 때문에 JSON 문자열이 보일 줄 알았는데 그렇지 않았습니다.나는 그것을 올바른 활자로 만들어야 했다.
예: 실패하였습니다.
[EnableCors("AllowAll")]
[HttpPost]
public HttpResponseMessage Post([FromBody]string value)
{
// Do something with the blog here....
var msg = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
return msg;
}
하지만 이건 성공했어.
[EnableCors("AllowAll")]
[HttpPost]
public HttpResponseMessage Post([FromBody]Blog value)
{
// Do something with the blog here....
var msg = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
return msg;
}
Ajax 콜
function HandleClick() {
// Warning - ID's should be hidden in a real application
// - or have covering GUIDs.
var entityData = {
"blogId": 2,
"url": "http://myblog.com/blog1",
"posts": [
{
"postId": 3,
"title": "Post 1-1",
"content": "This is post 1 for blog 1",
"blogId": 2
},
{
"postId": 4,
"title": "Post 1-2",
"content": "This is post 2 for blog 1",
"blogId": 2
}
]
};
$.ajax({
type: "POST",
url: "http://localhost:64633/api/blogs",
async: true,
cache: false,
crossDomain: true,
data: JSON.stringify(entityData),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (responseData, textStatus, jqXHR) {
var value = responseData;
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed.');
}
});
}
언급URL : https://stackoverflow.com/questions/14624306/web-api-parameter-always-null
'programing' 카테고리의 다른 글
워드프레스 사이트 제목과 태그라인을 표시하는 방법 (0) | 2023.02.26 |
---|---|
문자열에서 JSON 개체로 변환 Android (0) | 2023.02.26 |
angularjs $watch old 값과 new 값이 동일합니다. (0) | 2023.02.26 |
React Native에는 '가상 DOM'이 있습니까? (0) | 2023.02.26 |
AngularJS에서 양방향 필터링을 수행하는 방법은 무엇입니까? (0) | 2023.02.26 |