我想从承载API的同一个应用程序中获取一些ASP.NET API。现实世界的用例是我想将文件上传到MVC控制器,解析出来并通过对同一应用程序托管的API的POST请求进行一系列单独的API调用。我可以看到,通过在WebApi控制器方法中设置断点来获取相应的API端点,但有效负载始终为空。我尝试使用Flurl,RestSharp,WebClient和WebRequest来发出请求,但没有一个允许有效负载通过。如果我尝试通过单元/集成测试调用这些POST请求,它也会因空载荷问题而失败。
ASP.NET框架是否存在某种内置限制,阻止有效负载发布到同一个应用程序?
var myObjectRow = new JObject();
myObjectRow["Key"] = 1;
/* RestSharp */
var request = new RestRequest("/api/MyObject", Method.POST);
request.AddHeader("Content-type", "application/json; charset=utf-8");
request.AddBody(request.JsonSerializer.Serialize(myObjectRow));
request.AddJsonBody(myObjectRow);
request.AddParameter("Application/Json", myObjectRow, ParameterType.RequestBody);
var response = RestClient.Execute<MyObject>(request);
/* WebClient */
using (var webClient = new WebClient())
{
webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
var payload = JsonConvert.SerializeObject(myObjectRow);
var response = webClient.UploadString(BaseUrl + "/api/MyObject", "POST", payload);
}
/* WebRequest */
var payload = JsonConvert.SerializeObject(myObjectRow);
byte[] buf = Encoding.UTF8.GetBytes(payload);
var request = (HttpWebRequest)WebRequest.Create(BaseUrl + "/api/MyObject");
request.Method = "POST";
request.ContentLength = buf.Length;
request.ContentType = "application/json; charset=utf-8";
request.GetRequestStream().Write(buf, 0, buf.Length);
using (var response = (HttpWebResponse)request.GetResponse())
{
var responseStream = response.GetResponseStream();
var streamReader = new StreamReader(responseStream, Encoding.UTF8);
var responseString = streamReader.ReadToEnd();
}
目标端点是这样的:
public class MyObjectController : ApiController
{
public MyObject Post(MyObject myObject)
{
// myObject shows up null here
return myObject;
}
}
答案 0 :(得分:0)
试试这个:
public class MyObjectController : ApiController
{
public MyObject Post(MyObject myObject)
{
ModelState.Clear();
// myObject shows up null here
return myObject;
}
}
答案 1 :(得分:0)
我弄明白了这个问题。我正在使用的Excel阅读器将“.0”添加到整数字段,这导致反序列化在POST请求处理程序中以静默方式失败。有效载荷在没有这种不兼容性的情况下完成。
答案 2 :(得分:0)
尝试将myObjectRow重命名为myObject。我相信它希望参数具有相同的名称。