I have 3 web services added to service references in a class library.(This is a sample project for an API use) I need to move these into my project but i ca
If you using wcf service with json, you can implement sample post method i used in my one of projects. You need newtonsoft json package;
public static ResponseCL PostPurchOrder(PurchaseOrder order)
{
ResponseCL res = new ResponseCL();
string methodUrl = $"{_main.ws_url}/AddPurchaseOrder";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(methodUrl);
httpWebRequest.ContentType = "application/json;";
//if use basic auth//
//string username = "user";
//string password = "1234";
//string encoded = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(username + ":" + password));
//httpWebRequest.Headers.Add("Authorization", "Basic " + encoded);
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(JsonConvert.SerializeObject(order));
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
res = JsonConvert.DeserializeObject(result);
}
return res;
}
Another way using Microsoft.AspNet.WebApi.Client package like this;
public static ResponseCL PostPurchOrder2(PurchaseOrder order)
{
ResponseCL res = new ResponseCL();
using (var client = new HttpClient())
{
string methodUrl = $"{_main.ws_url}/AddPurchaseOrder";
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.PostAsJsonAsync(methodUrl, order);
response.Wait();
if (response.Result.IsSuccessStatusCode)
{
string responseString = response.Result.Content.ReadAsStringAsync().Result;
res = JsonConvert.DeserializeObject(responseString);
}
}
return res;
}