我正在使用 ASP.NET Web API,我玩得很开心。至少对于 GET。出于某种原因,当我尝试通过 jQuery$.post()
或发送数据时,我$.ajax()
收到的值ApiController
始终为空。更奇怪的是,用 Fiddler 向它发送数据就可以了。我确定这是我如何在 javascript 中构造对象的问题,但我似乎找不到它。这是代码:
// C#
[HttpPost]
public HttpResponseMessage BeginTrack([FromBody]string requestContext) {
// requestContext is always null. Except when it comes from Fiddler.
RequestContext ctx = null;
if (Request.Content.Headers.ContentType.MediaType == "application/json") {
try {
ctx = Json.Decode<RequestContext>(requestContext);
} catch (Exception ex) {
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError,
"An error has occured while processing your request. See Exception for details.", ex);
}
}
if (ctx == null) //...
和 jQuery...
getRequestContext = function (source, docType, id, ip) {
return {
SourceSite: source,
DocumentType: docType,
Id: id,
HostUrl: document.URL,
HostDomain: document.location.hostname,
IPAddress: ip,
UserAgent: navigator.userAgent,
Referrer: document.referrer
};
},
beginTracking = function (done, fail) {
var data = JSON.stringify(getRequestContext('none', 'P', 0, 'ip'));
$.post(
serviceBase + "/Tracking/BeginTrack",
data,
done,
"json"
).fail(fail);
}
更新:显然这在 ASP.NET WebForms (.NET 3.5) 中可以正常工作,但在同一个项目的 MVC4 中却不行...