【问题标题】:How do you post a JSON file to an ASP.NET MVC Action?如何将 JSON 文件发布到 ASP.NET MVC 操作?
【发布时间】:2013-03-10 01:20:00
【问题描述】:

我的 iphone 客户端将以下 json 发布到我的 mvc 服务。 当从 html 表单发布数据时,它会自动将表单数据转换为 UserModel 并将对象传递给我的 Create 方法,但是当我从 iphone 在我的请求正文中发送 JSON 字符串时,它会返回为 null。

从 JSON 到 Object 的转换最简洁的解决方案是什么。

我宁愿不为不同的客户端创建多个方法,所以我试图让相同的方法在 iphone 和 mvc 客户端上工作。

我的请求正文:

{
   "firstName" : "Some Name",
   "lastName" : "Some Last Name",
   "age" : "age"
}

我的模型和操作结果

public class UserModel
{
   public int Id { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public int Age { get; set; }
}

[HttpPost]
public Create ActionResult(UserModel user)
{
   // user is null
   userStorage.create(user);
   return SuccessResultForModel(user);
}

【问题讨论】:

  • 只是为了确认一下,你想把点击控制器的用户对象从json转换?
  • 您是否注册了 JsonValueProviderFactory(MVC 需要它才能解码 JSON 发布数据)?客户端是否指定了正确的 ContentType?请参阅stackoverflow.com/questions/4789481/… 了解其他要检查的事项(投票最多的答案有列表)。
  • 那个 JSON 看起来无效,“年龄”后面有一个逗号?另外,年龄的值应该是一个int? (虽然我认为失败了,它将使用默认的 int 值 0)。另外,你的HttpPost方法说Create Actionresult,不应该是ActionResult Create吗?
  • @DaveA 不,我还没有注册,我会试一试并回复谢谢

标签: c# asp.net asp.net-mvc


【解决方案1】:

您需要将 HTTP 标头accept 设置为“application/json”,以便 MVC 知道您在传递 JSON 并执行解释它的工作。

accept: application/json

在此处查看更多信息:http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html

更新:使用 MVC3 和 jQuery 的工作示例代码

控制器代码

namespace MvcApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult PostUser(UserModel data)
        {
            // test here!
            Debug.Assert(data != null);
            return Json(data);
        }
    }

    public class UserModel
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
    }
}

查看代码

@{ ViewBag.Title = "Index"; }
<script src="../../Scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
    var sample = {};
    sample.postData = function () {
        $.ajax({
            type: "POST", url: "@Url.Action("PostUser")",
            success: function (data) { alert('data: ' + data); },
            data: JSON.stringify({ "firstName": "Some Name", "lastName": "Some Last Name", "age": "30" }),
            accept: 'application/json'
        });
    };
    $(document).ready(function () {
        sample.postData();
    });
</script>

<h2>Index</h2>

** 更新 ** 在将其传递给 AJAX 请求中的 data 元素之前,我将 JSON.stringify 添加到 JS 对象。这只是使有效负载更具可读性,但是控制器将类似地解释data 的两种格式。

【讨论】:

  • 但是accept header只是告诉服务器客户端能够接收到什么。如其他问题中所述,设置内容类型标头就足够了:contentType: "application/json; charset=utf-8",
  • 这个答案对我来说似乎不正确。给出的代码确实“有效”,但是如果您查看 $.ajax() 发送的请求的实际正文,它不发送 JSON,它使用 application/x-www-form-urlencoded 格式,基本上是查询字符串格式。如果您将 jQuery 代码更改为实际发送 JSON,则 MVC 操作将不再起作用,因为未设置 contentType。请在此处查看我的答案stackoverflow.com/a/52205206/22194,以了解发送 JSON 并且确实有效的略有不同的版本。
  • @codeulike 我读了你的其他答案。如果你想设置返回的内容的 contentType,ASP.NET(以及更现代的版本,因为这篇文章提供了这种功能。
  • @AaronLS 问题中的示例代码在 MVC 操作上使用了 HttpPost 属性。如果您删除它,您可以使用 HTTP Get 访问端点,但我们还必须更改操作的最后一行,即我们返回内容的位置,例如 return Json(data, JsonRequestBehavior.AllowGet); - 默认情况下,我不相信 MVC操作可以从 HTTP Get 请求返回 JSON。
  • 此答案中的原始请求正文发布表单数据,而不是 json:firstName=Some+Name&amp;lastName=Some+Last+Name&amp;age=30。该 javascript 会将 JSON 对象传递给 data: 并将其序列化为此表单帖子。我只是想让其他人知道这不是您实际测试 JSON 模型绑定的方式,因为它实际上并没有发送 JSON 作为 HTTP Post 的正文。
【解决方案2】:

晚了,但希望对某人有所帮助。

从 JSON 到 Object 的转换最简洁的解决方案是什么?

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

$.post("http://localhost:52161/Default/PostRawJson/", { json: {
   "firstName" : "Some Name",
   "lastName" : "Some Last Name",
   "age" : "age"
}});


public void PostRawJson(string json)
{
    var person = System.Web.Helpers.Json.Decode(json);
    person.firstname...
}

这样您就可以根据要求在控制器中使用纯 JSON 对象。

【讨论】:

  • 当我尝试将 FormCollection 的 json 从控制器发布到其他服务时,这对我有很大帮助。谢谢。
  • 这确实有效,我喜欢你可以看到解码发生在哪里,而不是在 mvc 模型绑定器中通过魔法发生。
【解决方案3】:

我最近想出了一种更简单的方法来发布 JSON,并增加了从我的应用程序中转换模型的步骤。请注意,您必须为控制器创建模型 [JsonObject] 才能获取值并进行转换。

请求:

 var model = new MyModel(); 

 using (var client = new HttpClient())
 {
     var uri = new Uri("XXXXXXXXX"); 
     var json = new JavaScriptSerializer().Serialize(model);
     var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
     var response = await Client.PutAsync(uri,stringContent).Result;
     ...
     ...
  }

型号:

[JsonObject]
[Serializable]
public class MyModel
{
    public Decimal Value { get; set; }
    public string Project { get; set; }
    public string FilePath { get; set; }
    public string FileName { get; set; }
}

服务器端:

[HttpPut]     
public async Task<HttpResponseMessage> PutApi([FromBody]MyModel model)
{
    ...
    ... 
}

【讨论】:

    【解决方案4】:

    根据 Glenn Ferries 的回答,在我查看实际发送到控制器的内容之前,这似乎有效 - 它不是 JSON。

    因此稍作调整:

    这是 MVC 4 和 jQuery 1.7 ish

    控制器操作方法(有问题的 UserModel 对象):

    [HttpPost]
    public ActionResult Create(UserModel user)
    {
        Debug.Assert(data != null);
        return Json(data);
    }
    

    发送请求的jQuery代码:

    <script>
        $(function () {
            $.ajax({
                type: "POST",
                url: "@Url.Action("Create")",
                /* jQuery will not send JSON unless you explicitly tell it to */
                data: JSON.stringify({ "firstName": "Some Name", "lastName": "Some Last Name", "age": "30" }),
                /* contentType is important for MVC to be able to unpack the json */
                contentType: 'application/json'
                accept: 'application/json',
            }).done( function(data) {
                /* this callback gets used when successful */
                console.log("response: " + data);
            }).fail(function (jqxhr, status, error) {
                /* for debugging: this callback gets used in case of errors */
                console.log("error :" + error);
            }).always(function () {
                /* for debugging: this callback always gets called at the end either way*/
                console.log("complete");
            });
        });
    
    </script>
    

    MVC 控制器操作很简单。

    难点在于确保您实际上是在向它发送 JSON 以对其进行测试。

    jQuery ajax() 方法在与 POST 一起使用时通常会使用请求正文中的查询字符串格式对参数进行编码。 MVC 可以愉快地解压它。

    要使用 ajax() 实际发送 JSON,您必须使用 JSON.stringify()。

    为了让 MVC 正确解释该请求,您需要设置 contentType

    【讨论】:

      猜你喜欢
      • 2013-01-23
      • 1970-01-01
      • 2019-03-30
      • 2016-06-05
      • 2012-06-03
      • 1970-01-01
      • 2012-09-18
      • 2012-02-22
      • 1970-01-01
      相关资源
      最近更新 更多