Create Rest api C# code example
Example 1: c# make request to rest api
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
namespace ConsoleProgram
{
public class DataObject
{
public string Name { get; set; }
}
public class Class1
{
private const string URL = "https://sub.domain.com/objects.json";
private string urlParameters = "?api_key=123";
static void Main(string[] args)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(URL);
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync(urlParameters).Result;
if (response.IsSuccessStatusCode)
{
var dataObjects = response.Content.ReadAsAsync<IEnumerable<DataObject>>().Result;
foreach (var d in dataObjects)
{
Console.WriteLine("{0}", d.Name);
}
}
else
{
Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
client.Dispose();
}
}
}
Example 2: rest api in c#
curl https://localhost:5001/people/all
[{"name":"Ana"},{"name":"Felipe"},{"name":"Emillia"}]
Example 3: rest api in c#
[ApiController]
public class PeopleController : ControllerBase
{
[HttpGet("people/all")]
public ActionResult<IEnumerable<Person>> GetAll()
{
return new []
{
new Person { Name = "Ana" },
new Person { Name = "Felipe" },
new Person { Name = "Emillia" }
};
}
}
public class Person
{
public string Name { get; set; }
}