How to post JSON to a server using C#?

后端 未结 13 1616
臣服心动
臣服心动 2020-11-22 05:55

Here\'s the code I\'m using:

// create a request
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create(url); request.KeepAlive = false;
request.Protoco         


        
13条回答
  •  名媛妹妹
    2020-11-22 06:29

    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)
    {
        ...
        ... 
    }
    

提交回复
热议问题