asp.net之使用web API

http Get 方法请求获取数据,整个web API 的请求处理基于MVC框架

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 = "[email protected]"},
            new Users {UserID = 2, UserName = "Spiderman", UserEmail = "[email protected]"},
            new Users {UserID = 3, UserName = "Batman", UserEmail = "[email protected]"}
        };

        // 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));
        }
    }
}
构造 user list ,实现三个方法。

POST数据

实现一个User添加的功能,接受的类型为User实体,而我们POST的数据为对应的JSON数据。

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


HttpClient  +  ASP.NET  API  通过Json.NET 将需要传递的数据序列化为json字符串的

 

var requestJson = JsonConvert.SerializeObject(new { startId = 1, itemcount = 3 });

HttpContent httpContent = new StringContent(requestJson);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

var httpClient = new HttpClient();
var responseJson = httpClient.PostAsync("http://localhost:9000/api/demo/sitelist", httpContent)
    .Result.Content.ReadAsStringAsync().Result;
升级版为:

var responseJson = new HttpClient().PostAsJsonAsync("http://test.cnblogs.cc/api/demo/sitelist",
new { startId = 1, itemcount = 3 }).Result.Content.ReadAsStringAsync().Result;




猜你喜欢

转载自blog.csdn.net/quwujin/article/details/52868195