2

I have call to REST service from jscript that works fine:

post('/MySite/myFunct', { ID:22 })

How to make this call from C# in most native c# way?

UPD:

I need HTTPS solution also.

UPD:

And I need to use cookies

vico
  • 17,051
  • 45
  • 159
  • 315

2 Answers2

7
HttpClient client = new HttpClient();

var values = new Dictionary<string, string>
{
   { "ID", "22" }
};

var content = new FormUrlEncodedContent(values);

var response = await client.PostAsync("http://www.example.com", content);

var responseString = await response.Content.ReadAsStringAsync();
burning_LEGION
  • 13,246
  • 8
  • 40
  • 52
  • This works fine! But now I found that I need HTTPS. How to deal with that? – vico May 22 '17 at 09:57
  • Need to have a trusted SSL cert or your calls will fail with untrusted error. And addit to client: `WebRequestHandler handler = new WebRequestHandler(); X509Certificate2 certificate = GetMyX509Certificate(); handler.ClientCertificates.Add(certificate); HttpClient client = new HttpClient(handler);` – burning_LEGION May 22 '17 at 10:20
  • HTTPS also works! but now I need to make request, save cookie and use it in another request. How to achieve that? – vico May 22 '17 at 14:17
  • `HttpClient` has constructor with `HttpClientHandler`, it has public property `CookieContainer`, set Your cookies here – burning_LEGION May 22 '17 at 16:07
1

Old traditional way is using HttpClient / HttpWebRequest.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost/api/Test/TestPostData");
request.Method = "POST";
SampleModel model = new SampleModel();
model.PostData = "Test";
request.ContentType = "application/json";

JavaScriptSerializer serializer = new JavaScriptSerializer();
using (var sw = new StreamWriter(request.GetRequestStream()))
      {
                 string json = serializer.Serialize(model);
                 sw.Write(json);
                 sw.Flush();
      }
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Apart from this I prefer more Restclient /Restsharp from nuget.

A simple example of post request will be like this

using RestSharp;
using RestTest.Model;
private void button1_Click(object sender, EventArgs e)
{
    var client = new RestClient();
    var request = new RestRequest();
    request.BaseUrl = "http://carma.org";
    request.Action = "api/1.1/searchPlants";
    request.AddParameter("location", 4338);
    request.AddParameter("limit", 10);
    request.AddParameter("color", "red");
    request.AddParameter("format", "xml");
    request.ResponseFormat = ResponseFormat.Xml;
    var plants = client.Execute<PowerPlantsDTO>(request);
    MessageBox.Show(plants.Count.ToString());
} 

You can use HTTP Verbs directly from call

A Post example:

public void Create(Product product)
{
  var request = new RestRequest("Products", Method.POST); < ----- Use Method.PUT for update
  request.AddJsonBody(product);
  client.Execute(request);
}

A Delete Example

public void Delete(int id)
{
  var request = new RestRequest("Products/" + id, Method.DELETE);
  client.Execute(request);
}

For adding header in request

request.AddHeader("data", "test");

A Get Request

private RestClient client = new RestClient("http://localhost:8080/api/");
RestRequest request = new RestRequest("Products", Method.GET);

RestResponse<YourDataModel> response = client.Execute<YourDataModel>(request);
var name = response.Data.Name;
Navoneel Talukdar
  • 4,393
  • 5
  • 21
  • 42