将 JSON 发布到 MVC5 ASP.NET?(不是网络 API)



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

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

型:

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 发布到操作中?在我的情况下,模型的所有属性都是空的。

我只是使用这些代码,它在 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();
        }

最新更新