【问题标题】:POST JSON to ASP.NET MVC5? (NOT web API)将 JSON 发布到 ASP.NET MVC5? (不是网络 API)
【发布时间】:2017-10-27 10:49:36
【问题描述】:

有没有办法将 JSON 数据发布到 MVC5 操作? 不是 WebAPI!

问题是:我的动作被调用,但传入模型的所有属性都是空的。

型号:

using Newtonsoft.Json;

[JsonObject()]
[Serializable()]
public class DemoModel
{
    [JsonProperty()]
    public string a { get; set; }

    [JsonProperty()]
    public string b { get; set; }
}

动作是:

[HttpPost()]
public ActionResult demoaction(DemoModel model)
{
    //model.a here is null, should be "AAA"
    //model.b here is null, should be "BBB"
}

我一直在使用 Fiddler 来模拟请求。我的 POST 请求如下所示:

POST http://localhost:9000/demoaction HTTP/1.1
Host: localhost:9000
Connection: keep-alive
Accept: */*
Content-Type: application/json
Content-Length: 60

身体是这样的:

{"a":"AAA","b":"BBB"}

那么,问题又来了:如何将 JSON 发布到操作中?在我的情况下,模型的所有属性都是空的。

【问题讨论】:

  • FromBody 属性在非 WebAPI 中不可用:/
  • 你是对的。我很抱歉

标签: json post asp.net-mvc-5 json.net


【解决方案1】:

我只是使用这些代码,它在 MVC5 操作上运行良好 但请确保您在 POST 请求标头中使用Content-Type : application/json,否则它将无法正常工作并且模型仍将为空

public class DemoModel
    {

        public string a { get; set; }


        public string b { get; set; }
    }

[HttpPost]
        public ActionResult Index(DemoModel model)
        {

            return View();
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-30
    • 2014-08-24
    • 1970-01-01
    • 2021-07-20
    相关资源
    最近更新 更多