Use C # code to call the Web API

1. POST

POST parameters need to add [FromBady], and the parameters can only be a

When submitting data to the client ContentType application / x-www-form-urlencoded or application / json and have little impact.

If the data is simple, key-value key of the plane, then use the application / x-www-form-urlencoded simple, practical, no additional codecs

If the data is complex nested relation, there are multiple levels of data, then use the application / json simplify processing data

C # client code

  1 var postData = new
  2             {
  3                 day = day.ToString("yyyy-MM-dd")
  4             };
  5             var content = new StringContent(JsonHelper.ConvertToStr(postData));//用的StringContent 之前用的FormUrlEncodedContent
  6             content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
  7             HttpClient myHttpClient = new HttpClient();
  8             myHttpClient.BaseAddress = new Uri("http://localhost:54455");
  9             var response = myHttpClient.PostAsync("API/ProductionCalendar/Create", content).Result;
View Code

C # server code

  1 [HttpPost]
  2 
  3 public bool Create([FromBody]JObject parameters)
  4 
  5 {
  6 
  7 dynamic d = parameters;
  8 
  9 DateTime dt;
 10 
 11 if (DateTime.TryParse(d.day.ToString(), out dt) == false)
 12 
 13 throw new Exception($"{d.day} 时间格式不正确!");
 14 
 15 return _calendarDomain.Create(dt);
 16 
 17 }
 18 
View Code

Description: Use JObject corresponding type as a parameter, and then use dynamic type dynamic acquisition parameters

clipboard

PS: If the parameter type is a value type or interface string, the data submitted

Attachment:

https://www.cnblogs.com/landeanfen/p/5177176.html

Guess you like

Origin www.cnblogs.com/smallidea/p/11995852.html