asp.net web api定义案例一

asp.net web api定义案例一

using Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

namespace WebApi
{
    /// <summary>
    /// api/Contacts
    /// </summary>
    public class ContactsController : ApiController
    {
        static List<Contact> contacts;
        static ContactsController()
        {
            contacts = new List<Contact>();
            contacts.Add(new Contact
            {
                Id = "001",
                Name = "张三",
                PhoneNo = "0512-12345678",
                EmailAddress = "[email protected]",
                Address = "四川省成都市星湖街328号"
            });
            contacts.Add(new Contact
            {
                Id = "002",
                Name = "李四",
                PhoneNo = "0512-12345678",
                EmailAddress = "[email protected]",
                Address = "四川省成都市金鸡大道328号"
            });
        }
        //获取当前联系人列表 Get api/Contacts   OK
        public IEnumerable<Contact> Get(string id = null)
        {
            int cCount=contacts.Count;
            //
            return from c in contacts
                   where c.Id == id || string.IsNullOrEmpty(id)
                   select c;
        }
        //post 添加新的联系人  OK
        public void Post(Contact c)
        {
            int cCount = contacts.Count();
            cCount += 1;
            c.Id = cCount.ToString().PadLeft(3, '0');  //System.Guid.NewGuid().ToString();
            //
            contacts.Add(c);
        }
        //-----put selfhost OK
        public void Put(Contact ct)
        {
            contacts.Remove(contacts.First(c =>c.Id == ct.Id));
            contacts.Add(ct);
        }
        public void Delete(string id)
        {
            contacts.Remove(contacts.First(c => c.Id == id));
        }
        //-----
    }

}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace Common
{
    //[DataContract, Serializable]
    /// <summary>
    /// 上面的代码不能添加,添加了就获取不到类中具体的属性值
    /// vp:hsg
    /// create date:2018-04/05
    /// </summary>
    public class Contact
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string PhoneNo { get; set; }
        public string EmailAddress { get; set; }
        public string Address { get; set; }
    }
}

猜你喜欢

转载自blog.csdn.net/hsg77/article/details/80294020