【发布时间】:2015-05-30 02:25:04
【问题描述】:
我在 web api 控制器中有一个 web api 方法,如下所示,它运行良好..
[Route("api/myquery")]
[HttpPost]
public HttpResponseMessage MyQuery([FromBody] string id)
{
if (string.IsNullOrEmpty(id))
{
return new HttpResponseMessage(HttpStatusCode.BadRequest);
}
return new HttpResponseMessage(HttpStatusCode.OK);
}
我想在我的 asp.net mvc 控制器中使用类似的控制器..
我尝试了以下..
[HttpPost]
public ActionResult MyQuery(string id)
{
return this.Content("");
}
发布的数据是从 javascript 中的相同方法发送的。
$.ajax("/api/myquery", {
data: JSON.stringify(tmp1),
type: "post", contentType: "application/json",
success: function (result) { alert("Saved Successfully") },
error: function (result) { alert("Error Saving") }
});
但是,由于 MVC 没有 [FromBody] 标签,我无法访问正在发送的内容。虽然正在调用该方法,但 id 始终显示为 null...
【问题讨论】:
-
假设
tmp1是{ id: someValue }那么你需要指定正确的url -url: '/yourControllerName/myquery',或者更好的url: '@Url.Action("myquery", "yourControllerName")', -
正在访问该方法,这意味着光标在调试时到达该方法内部,但 id 始终为空
-
你确定
tmp1的值是{ id: someValue }吗? -
关键是 { id: someValue } 只有 tmp 没有 id 这就是为什么 id 为 null, tx..
标签: asp.net-mvc asp.net-mvc-4 asp.net-web-api asp.net-mvc-5