我正在使用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);
}
UPDATE :显然,这在ASP.NET WebForms(.NET 3.5)中运行良好,但在同一项目中的MVC4中却不行......
答案 0 :(得分:5)
您需要从jquery发送"=mystring"
而不是"mystring"
。这是一个已知问题,这是由于数据在Web API中的映射方式。