How to post data to specific URL using WebClient in C#

后端 未结 8 1680
深忆病人
深忆病人 2020-11-22 07:12

I need to use \"HTTP Post\" with WebClient to post some data to a specific URL I have.

Now, I know this can be accomplished with WebRequest but for some reasons I wa

8条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 08:02

    Using webapiclient with model send serialize json parameter request.

    PostModel.cs

        public string Id { get; set; }
        public string Name { get; set; }
        public string Surname { get; set; }
        public int Age { get; set; }
    

    WebApiClient.cs

    internal class WebApiClient  : IDisposable
      {
    
        private bool _isDispose;
    
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    
        public void Dispose(bool disposing)
        {
            if (!_isDispose)
            {
    
                if (disposing)
                {
    
                }
            }
    
            _isDispose = true;
        }
    
        private void SetHeaderParameters(WebClient client)
        {
            client.Headers.Clear();
            client.Headers.Add("Content-Type", "application/json");
            client.Encoding = Encoding.UTF8;
        }
    
        public async Task PostJsonWithModelAsync(string address, string data,)
        {
            using (var client = new WebClient())
            {
                SetHeaderParameters(client);
                string result = await client.UploadStringTaskAsync(address, data); //  method:
        //The HTTP method used to send the file to the resource. If null, the default is  POST 
                return JsonConvert.DeserializeObject(result);
            }
        }
    }
    

    Business caller method

        public async Task GetResultAsync(PostModel model)
        {
            try
            {
                using (var client = new WebApiClient())
                {
                    var serializeModel= JsonConvert.SerializeObject(model);// using Newtonsoft.Json;
                    var response = await client.PostJsonWithModelAsync("http://www.website.com/api/create", serializeModel);
                    return response;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
    
        }
    

提交回复
热议问题