在我的方法上编写一个web api项目和一个参数(这是一个json数组)进入api null。我打电话的jquery看起来像这样:
<script>
$(document).ready(function () {
$('#btnSubmit').click(function () {
var jsRequestAction = {
appId: 'appName',
custId: 'custId',
oprId: 'oprId',
businessProcess: 'Requisition',
action: 'Approve',
actionKeys: [
'blah blah 1',
'blah blah 2',
'blah blah 3'
]
};
$.ajax({
type: "POST",
content: "json",
url: "http://localhost/api/appName/custId/oprId",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ requestAction: jsRequestAction })
});
});
});
</script>
我的网络api方法如下所示:
public IList<ResponseAction> ActionCounter(string appName, string custCode, string custUserName, RequestAction requestAction)
{
IList<ResponseAction> actionResponseList = new List<ResponseAction>();
var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
conn.Open();
try
{
foreach (string s in requestAction.actionKeys)
{
var command = new SqlCommand
{
CommandText = "Sql statement",
Connection = conn
};
command.ExecuteNonQuery();
var reply = new ResponseAction();
reply.responseActionKey = s;
reply.responseMessage = "Success";
actionResponseList.Add(reply);
}
return actionResponseList;
}
finally
{
conn.Close();
conn.Dispose();
}
}
RequestAction模型:
public class RequestAction
{
public string appId { get; set; }
public string custId { get; set; }
public string oprId { get; set; }
public string businessProcess { get; set; }
public string action { get; set; }
public string[] actionKeys { get; set; }
public string actionKey { get; set; }
}
当我调试时,我逐步完成该方法,当我到达foreach循环时,我得到一个空对象引用。查看我的locals部分,requestAction的所有属性都为null。在阅读了一些相关文章之后,我尝试使用[FromBody]标签为对象添加前缀无效。任何帮助将不胜感激。
答案 0 :(得分:1)
我找到了问题HERE的答案。这是改变这个问题:
$.ajax({
type: "POST",
content: "json",
url: "http://localhost/api/appName/custId/oprId",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ requestAction: jsRequestAction })
});
到此:
$.ajax({
type: "POST",
content: "json",
url: "http://localhost/api/appName/custId/oprId",
data: jsRequestAction
});
否则,数据将不会绑定到控制器中的模型,并且所有内容都将被清除。
答案 1 :(得分:0)
您需要确保对象服务器端与您正在创建客户端的对象匹配,以便可以将请求直接序列化到对象中。
所以你的行动方法将如下所示:
public IList<ResponseAction> ActionCounter(RequestAction requestAction)
{
// Do stuff
}
RequestAction应与您正在创建的javascript对象匹配。