我想從託管API的同一應用程序中擊中一些ASP.NET API。真實世界的用例是我想將文件上傳到MVC控制器,解析出來,並通過POST請求向同一應用程序託管的API進行一系列單獨的API調用。通過在WebApi控制器方法內部設置斷點,我可以看到適當的API端點正在被擊中,但有效負載始終爲空。我已經嘗試使用Flurl,RestSharp,WebClient和WebRequest來發出請求,而且它們都不允許有效負載通過。如果我嘗試通過單元/集成測試調用這些POST請求,它也會失敗,出現空有效負載問題。對同一主機的ASP.NET 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;
}
}
如果將api更改爲接收字符串而不是JSON,會發生什麼情況? –
可能是兩個問題之一。 (1)表單主體不包含在HTTP請求中,或者(2)表單主體具有內容,但是從表單主體到'MyObject'的綁定/映射失敗,可能是由於解析問題。檢查日誌並讓我們知道其中哪些正在發生,因爲答案會非常不同。 –