Config ให้ Dynamic สำหรับ Develop With Asp.net WEP Api
Note** ใช้งาน Asp.net WEB API2 and .net framework 4.5
ให้เพิ่มโค้ดนี้ลงไปที่ WebApiConfig.cs
config.Routes.MapHttpRoute("DefaultApiWithId", "api/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" });
config.Routes.MapHttpRoute("DefaultApiWithAction", "api/{controller}/{action}");
config.Routes.MapHttpRoute("DefaultApiGet", "api/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) });
config.Routes.MapHttpRoute("DefaultApiPost", "api/{controller}", new { action = "Post" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Post)
});
พร้อมกับ Comment Config เดิมที่ให้มา
//config.Routes.MapHttpRoute(
// name: "DefaultApi",
// routeTemplate:
"api/{controller}/{id}",
// defaults: new { id =
RouteParameter.Optional }
//);
แค่นี้ก็เรียบร้อย ตัวอย่างโค้ด
public class ProductController : ApiController
{
PD1[] products = new PD1[]
{
new PD1 {ID= 1, A_PDNAME = "Tomato
Soup", A_PDDESC = "Groceries"},
new PD1 { ID = 2, A_PDNAME = "Yo-yo", A_PDDESC = "Toys" },
new PD1 { ID = 3, A_PDNAME = "Hammer", A_PDDESC = "Hardware"}
};
// GET
api/Product
public IEnumerable<PD1> Get()
{
return products;
}
// GET
api/ Product/5
public PD1 Get(int id)
{
return products.Where(c => c.ID == id).FirstOrDefault();
}
// GET api/ Product?id=aa &name=??
public PD1 Get(int id, string name)
{
return products.Where(c => c.ID == id &&
c.A_PDNAME.Contains(name)).FirstOrDefault();
}
// GET api/ Product/GetByname? name=??
public IEnumerable<PD1> GetByName(string name)
{
return products.ToList();
}
}
ไม่มีความคิดเห็น:
แสดงความคิดเห็น