How do you post a JSON file to an ASP.NET MVC Action?

前端 未结 5 1622
予麋鹿
予麋鹿 2020-12-01 18:51

My iphone client posts the following json to my mvc service. When posting data from html form it automatically converts form data to UserModel and passes the object to my Cr

5条回答
  •  情书的邮戳
    2020-12-01 19:23

    I recently came up with a much simpler way to post a JSON, with the additional step of converting from a model in my app. Note that you have to make the model [JsonObject] for your controller to get the values and do the conversion.

    Request:

     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;
         ...
         ...
      }
    

    Model:

    [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; }
    }
    

    Server side:

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

提交回复
热议问题