Created
December 9, 2013 09:35
-
-
Save tomasherceg/7869699 to your computer and use it in GitHub Desktop.
Kurz ASP.NET Web API - třída ProductsController
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ProductsController : ApiController | |
{ | |
private static Dictionary<int, Product> products = new Dictionary<int, Product>(); | |
static ProductsController() | |
{ | |
products.Add(1, new Product() { Name = "Rohlík", Category = "Jídlo", UnitsOnStock = 100 }); | |
products.Add(2, new Product() { Name = "Hrábě", Category = "Nářadí", UnitsOnStock = 5 }); | |
products.Add(3, new Product() { Name = "Coca Cola", Category = "Nápoje", UnitsOnStock = 10 }); | |
} | |
// GET api/<controller> | |
public IEnumerable<KeyValuePair<int, Product>> Get( | |
string name = null, | |
string category = null, | |
int? minUnitsOnStock = null, | |
int? maxUnitsOnStock = null) | |
{ | |
IEnumerable<KeyValuePair<int, Product>> data = products; | |
if (!string.IsNullOrEmpty(name)) | |
{ | |
data = data.Where(d => d.Value.Name.Contains(name)); | |
} | |
if (!string.IsNullOrEmpty(category)) | |
{ | |
data = data.Where(d => d.Value.Category == category); | |
} | |
if (minUnitsOnStock != null) | |
{ | |
data = data.Where(d => d.Value.UnitsOnStock > minUnitsOnStock.Value); | |
} | |
if (maxUnitsOnStock != null) | |
{ | |
data = data.Where(d => d.Value.UnitsOnStock < maxUnitsOnStock.Value); | |
} | |
return data; | |
} | |
// GET api/<controller>/5 | |
public HttpResponseMessage Get(int id) | |
{ | |
var response = new HttpResponseMessage(HttpStatusCode.OK); | |
response.Content = new ObjectContent(typeof(Product), products[id], new JsonMediaTypeFormatter()); | |
response.Headers.Add("X-Entity-Id", id.ToString()); | |
return response; | |
//var response = Request.CreateResponse(HttpStatusCode.OK, products[id]); | |
//response.Headers.Add("X-Entity-Id", id.ToString()); | |
//return response; | |
} | |
// POST api/<controller> | |
public HttpResponseMessage Post(Product value) | |
{ | |
var id = products.Keys.DefaultIfEmpty(0).Max() + 1; | |
products.Add(id, value); | |
var response = new HttpResponseMessage(HttpStatusCode.Redirect); | |
response.Headers.Location = new Uri("/api/Products/" + id, UriKind.Relative); | |
return response; | |
} | |
// PUT api/<controller>/5 | |
public void Put(int id, Product value) | |
{ | |
if (!products.ContainsKey(id)) | |
{ | |
throw new HttpResponseException(HttpStatusCode.NotFound); | |
} | |
products[id] = value; | |
} | |
// DELETE api/<controller>/5 | |
public void Delete(int id) | |
{ | |
if (!products.Remove(id)) | |
{ | |
throw new HttpResponseException(HttpStatusCode.NotFound); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment