【问题标题】:Converting a asp.net mvc webapi method to asp.net mvc method将 asp.net mvc webapi 方法转换为 asp.net mvc 方法
【发布时间】: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


【解决方案1】:

试试这个

      [HttpPost]
      public ActionResult MyQuery(string id)
      {
          if (string.IsNullOrEmpty(id))
          {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
          }
          return Json("message","text/json",JsonRequestBehavior.AllowGet);      
      }

并在 ajax 帖子中更改您的 url(将 api 替换为您的控制器名称:例如,如果您在家庭控制器下,请输入“home”)

$.ajax("home/myquery", {
    /*data: JSON.stringify(tmp1),*/
    data:  JSON.stringify({id:tmp1}),
    type: "post", contentType: "application/json",
    success: function (result) { alert("Saved Successfully") },
    error: function (result) { alert("Error Saving") }
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-02
    • 2014-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-02
    • 2011-08-16
    • 2011-02-11
    相关资源
    最近更新 更多