我在向WebAPI2控制器发送值数组时遇到了困难。 最初在这里问到:Complex input to WebApi2 function
我在尝试使用ajax发送值时遇到问题,ajax方法仅用于测试此Action并且操作实际上是 在生产代码中使用WebClient对象调用,如下所示。似乎当我进入Action时,VP参数未被正确读取。
我已经使用POST和GET尝试了相同的结果。关于我在这里做错了什么的想法?
当我在Action中检查它时,这是来自Request的URL:
http://localhost:49494/api/GetDocs?LT=c40210542a802cac4ca5fc96eaa2c3bfef592418b5&PID=1158341&VP[0][Name]=RID&VP[0][Value]=1158341&ER=100&SR=1&SB=DOCNAME+ASC
这是发送数据的Ajax调用:
var _url = "http://localhost:49494/api/GetDocs";
var postdata = {
"LT": "c40210542a802cac4ca5fc96eaa2c3bfef592418b5",
"PID": 1158341,
// VP may have more than one 'set' of values
// This is essentially a list of fields and values to filter a dataset
"VP":[{"Name":"RID","Value":"1158341"}],
"ER": 100,
"SR": 1,
"SB": "DOCNAME ASC",
}
$.ajax({
async: true,
cache: false,
traditional: true, // Yes I am setting this to true!
contentType: 'application/x-www-form-urlencoded',
url: _url,
type: 'GET',
// type: 'POST',
data: postdata,
beforeSend: function () {
console.log('Fired prior to the request');
},
success: function (data) {
console.log('Fired when the request is successfull');
$('.document').append('<p>Success :' + data + '</p>');
},
complete: function () {
console.log('Fired when the request is complete');
},
error: function (jqxhr, status, errorThrown) {
$('.document').append('<p>Error :' + jqxhr.responseText + '</p>');
}
});
以下是从另一个MVC应用程序在生产代码中发送它的方式:
// request object will be passed to the method.
string returnjson = "";
using (WebClient client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/json";
url = "http://mywebapiapp.com/api/GetDocs";
string json = JsonConvert.SerializeObject(request);
byte[] data = Encoding.UTF8.GetBytes(json);
byte[] result = client.UploadData(url, data);
returnjson = Encoding.UTF8.GetString(result);
}
return returnjson
这是我的WebAPI2控制器操作。我尝试了List<string>
和string[]
。 VP参数的值始终为空。
[HttpGet]
[Route("api/GetDocs")]
[EnableCors("http://localhost:49494", // Origin
"Accept, Origin, Content-Type, Options", // Request headers
"GET", // HTTP methods
PreflightMaxAge = 600 // Preflight cache duration
)]
public IHttpActionResult GetDocs(string LT, int PID, List<string> VP, int SR = 1, int ER = 100, string SB = "")
{
string msg = "";
try
{
var result = _Repository.getDocuments(LT, PID, VP.ToArray(), SR, ER, SB);
string resultstring = Newtonsoft.Json.JsonConvert.SerializeObject(result);
// Now send results back...
return Ok(result);
}
catch (Exception ex)
{
/*
log.WriteToEventLog(msg, "error");
log.WriteToEventLog(ex.Message, "error");
*/
throw ex;
}
}
答案 0 :(得分:0)
对于您发送的结构化数据类型,我建议使用POST而不是GET。
通过几个步骤完成您的示例:
{{1}}
要点:
声明要用作dto的复杂类型
将HttpPost属性添加到GetDocs操作,然后用TestVm实例替换所有参数
将您的请求的contenttype标题更改为&#39; application / json&#39;
将您的数据转换为JSON
希望这有帮助!