// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; using System.Collections.Generic; using System.Net; using System.Runtime.Serialization; using System.Web.Http; using Microsoft.AspNetCore.Cors; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Ws.Rest { [DataContract(Name="t1",Namespace="")] public class T1 { [DataMember(Name="f1")] public int F1 { get; set; } [DataMember(Name="f2")] public string F2 { get; set; } public T1() : this(0, "") { } public T1(int f1, string f2) { this.F1 = f1; this.F2 = f2; } } [CollectionDataContract(Name="t1array",Namespace="")] public class T1Array : List { public T1Array() : this(new T1[0]) { } public T1Array(T1[] array) : base(array) { } } public class Test { public T1 GetOne(int f1) { // dummy implementation return new T1(f1, "getOne"); } public T1[] GetAll() { // dummy implementation T1[] res = new T1[3]; res[0] = new T1(1, "getAll #1"); res[1] = new T1(2, "getAll #2"); res[2] = new T1(3, "getAll #3"); return res; } public T1[] GetSome(int start, int finish) { // dummy implementation T1[] res = new T1[finish - start + 1]; for(int i = 0; i < res.Length; i++) { res[i] = new T1(start + i, "getSome #" + (start + i)); } return res; } public bool Save(T1 o) { // dummy implementation return o.F1 > 0 && o.F2.Length > 0; } public bool Delete(int f1) { // dummy implementation return f1 > 0; } } [Route("/t1")] ////[EnableCors("AlmostAnythingGoes")] [ApiController] public class TestApiController : ControllerBase { private Test real = new Test(); [HttpGet("{f1}")] public IActionResult GetOne(int f1) { return Ok(real.GetOne(f1)); } [HttpGet("")] public IActionResult GetSome(int start = 0, int finish = 2147483647) { if(start == 0 && finish == 2147483647) { return Ok(new T1Array(real.GetAll())); } else { return Ok(new T1Array(real.GetSome(start, finish))); } } [HttpPost("")] public IActionResult Save(T1 o) { if(real.Save(o)) { return Ok(o); } else { return NotFound(); } } [HttpPut("{f1}")] public IActionResult Update(int f1, T1 o) { if(f1 == o.F1 && real.Save(o)) { return StatusCode(StatusCodes.Status204NoContent); } else { return NotFound(); } } [HttpDelete("{f1}")] public IActionResult Delete(int f1) { if(real.Delete(f1)) { return StatusCode(StatusCodes.Status204NoContent); } else { return NotFound(); } } } }