网络阿比参数总是空 [英] Web Api Parameter always null
问题描述
为什么参数总是空当我打电话下面的Post方法与下面的AJAX?
公开的IEnumerable<字符串>帖子([FromBody]字符串值)
{
返回新的String [] {值1,值2,值};
}
下面是调用通过AJAX网页API方法:
函数SearchText(){
$(#txtSearch)。自动完成({
来源:功能(请求,响应){
$阿贾克斯({
键入:POST,
的contentType:应用/ JSON的;字符集= UTF-8,
网址:API /搜索/,
数据:测试,
数据类型:文本,
成功:功能(数据){
响应(data.d);
},
错误:函数(结果){
警报(错误);
}
});
}
});
}
$。阿贾克斯({
网址:/ API /搜索,
键入:POST,
的contentType:应用程序/ x-WWW的形式urlen codeD;字符集= UTF-8,
数据:'='+ EN codeUriComponent(request.term)
成功:功能(数据){
响应(data.d);
},
错误:函数(结果){
警报(错误);
}
});
基本上,你可以拥有它是装饰与 [FromBody]
属性标量型只有一个参数和您的要求需要使用应用程序/ x -www外形urlen codeD
和POST有效载荷应该是这样的:
= someValue中
请注意,违反标准协议的参数名称丢失。您只发送了价值。
您可以了解更多有关如何模型在Web阿比结合工程<一href="http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-1"><$c$c>this文章 。
不过,当然这个黑客周围是一个生病的事情。您应该使用视图模型:
公共类MyViewModel
{
公共字符串值{获得;组; }
}
,然后摆脱 [FromBody]
属性:
公开的IEnumerable&LT;字符串&GT;帖子(MyViewModel模型)
{
返回新的String [] {值1,值2,model.Value};
}
,然后使用JSON请求:
$。阿贾克斯({
网址:/ API /搜索,
键入:POST,
的contentType:应用/ JSON的;字符集= UTF-8,
数据:JSON.stringify({值:request.term}),
成功:功能(数据){
响应(data.d);
},
错误:函数(结果){
警报(错误);
}
});
Why is the parameter always null when I call the below Post method with the below ajax?
public IEnumerable<string> Post([FromBody]string value)
{
return new string[] { "value1", "value2", value };
}
Here is the call to the Web API method via ajax:
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');
}
});
Basically you can have only one parameter of scalar type which is decorated with the [FromBody]
attribute and your request needs to use application/x-www-form-urlencoded
and the POST payload should look like this:
=somevalue
Notice that contrary to standard protocols the parameter name is missing. You are sending only the value.
You can read more about how model binding in the Web Api works in this article
.
But of course this hacking around is a sick thing. You should use a view model:
public class MyViewModel
{
public string Value { get; set; }
}
and then get rid of the [FromBody]
attribute:
public IEnumerable<string> Post(MyViewModel model)
{
return new string[] { "value1", "value2", model.Value };
}
and then use a JSON request:
$.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');
}
});
这篇关于网络阿比参数总是空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!