基本信息
源码名称:Asp.Net Web API GET POST 实例源码下载
源码大小:2.43M
文件格式:.zip
开发语言:C#
更新时间:2014-06-12
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300

本次赞助数额为: 2 元 
   源码介绍
实现了基本 get post 请求,并可以输出xml 或者json

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebAPI.Models;

namespace WebAPI.Controllers
{
    public class UsersController : ApiController
    {
        /// <summary>
        /// User Data List
        /// </summary>
        private readonly List<Users> _userList = new List<Users>
        {
            new Users {UserID = 1, UserName = "Superman", UserEmail = "Superman@cnblogs.com"},
            new Users {UserID = 2, UserName = "Spiderman", UserEmail = "Spiderman@cnblogs.com"},
            new Users {UserID = 3, UserName = "Batman", UserEmail = "Batman@cnblogs.com"}
        };

        // GET api/Users
        public IEnumerable<Users> Get()
        {
            return _userList;
        }

        // GET api/Users/5
        public Users GetUserByID(int id)
        {
            var user = _userList.FirstOrDefault(users => users.UserID == id);
            if (user == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return user;
        }

        //GET api/Users/?username=xx
        public IEnumerable<Users> GetUserByName(string userName)
        {
            return _userList.Where(p => string.Equals(p.UserName, userName, StringComparison.OrdinalIgnoreCase));
        }

        //POST api/Users/Users Entity Json
        public Users Add([FromBody]Users users)
        {
            if (users == null)
            {
                throw new HttpRequestException();
            }
            _userList.Add(users);
            return users;
        }

        public void Delete(int id)
        {
            _userList.RemoveAll(p => p.UserID == id);
        }
    }
}