码迷,mamicode.com
首页 > Windows程序 > 详细

ASP.NET Web API 实例

时间:2014-06-26 19:21:32      阅读:455      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   http   tar   

ASP.NET Web API 入门大杂烩

 

创建Web API解决方案,命名为VCoinWebApi,并且创建了同名的Project,然后,创建一个Empty Project:Models,创建一个WPF Application Project:VCoinWebTester

bubuko.com,布布扣

 

在Models项目下,添加User类。User类的代码如下:

namespace Models
{
    public class User
    {
        public long ID { get; set; }
        public string UserName { get; set; }
        public Platform Platform { get; set; }
        public string Status { get; set; }
    }

    public enum Platform
    {
        Facebook,
        Youtube
    }
}

在VCoinWebApi项目下的Controllers文件夹上右键添加Web API 2 Controller - Empty。新建的UsersController代码如下:

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

using Models;
using Newtonsoft.Json.Linq;

namespace VCoinWebApi.Controllers
{
    public class UsersController : ApiController
    {
        List<User> users = new List<User>
        { 
            new User { ID = 1, UserName = "Soup1", Platform = Platform.Facebook, Status = "User" },
            new User { ID = 2, UserName = "Soup2", Platform = Platform.Facebook, Status = "User" },
            new User { ID = 3, UserName = "Soup3", Platform = Platform.Facebook, Status = "User" }, 
            new User { ID = 4, UserName = "Soup4", Platform = Platform.Facebook, Status = "User" }, 
        };

        public IEnumerable<User> GetAllUsers()
        {
            return users;
        }

        public User GetUserById(short id)
        {
            var user = users.FirstOrDefault((p) => p.ID == id);
            if (user == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            else
            {
                return user;
            }
        }

        [HttpGet]
        [ActionName("GetUser")]
        public IEnumerable<User> GetUsersByName(string userName)
        {
            return users.Where(
                (p) => string.Equals(p.UserName, userName,
                    StringComparison.OrdinalIgnoreCase));
        }

        [HttpPost]
        [ActionName("AddUser")]
        public User Add([FromBody]long id, string userName,int platform,string status)
        {
            User user = new User { ID = id, UserName = userName, Platform = (Platform)platform, Status = status };
            if (user == null)
            {
                throw new HttpRequestException();
            }
            users.Add(user);
            return user;
        }

        [HttpPost]
        [ActionName("AddUser")]
        public User AddUser([FromBody]User user)
        {
            if (user == null)
            {
                throw new HttpRequestException();
            }
            users.Add(user);
            return user;
        }

        [HttpPost]
        public User Delete([FromBody]int id)
        {
            var user = users.FirstOrDefault((p) => p.ID == id);
            if (user == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            else
            {
                users.Remove(user);
                return user;
            }
        }

        [HttpPost]
        [ActionName("Update")]
        public HttpResponseMessage UpdateUser([FromUri]int id,[FromBody]User user)//{"ID":1,"UserName":"Hello","Platform":1,"Status":"User"}
        {
            return Request.CreateResponse(HttpStatusCode.OK, user);
        }

        //[HttpPost]
        //[ActionName("Update")]
        //public HttpResponseMessage UpdateUser(JObject jo)//{"ID":1,"UserName":"Hello","Platform":1,"Status":"User"}
        //{
        //    User user = new User();
        //    user.ID = 1;
        //    user.Platform = Platform.Youtube;
        //    user.Status = "User";
        //    user.UserName = "Hello";

        //    return Request.CreateResponse(HttpStatusCode.OK, user);
        //}

        //[HttpPost]
        //[ActionName("Update")]
        //public void UpdateUser(JObject jo)//不返回值
        //{
           
        //}

        //[HttpPost]
        //[ActionName("Update")]
        //public bool UpdateUser(JObject jo)//返回:true
        //{
        //    return true;
        //}
    }
}

修改App_Start文件夹下的WebApiConfig.cs文件的默认的路由规则,如下:

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.EnableSystemDiagnosticsTracing();
        }
    }

在VCoinWebTester项目下添加WebApiRequest.cs类,类的主要的两个方法如下:

     /// <summary>
        /// Post data to server
        /// </summary>
        /// <param name="postData"></param>
        /// <param name="builderPath"></param>
        /// <param name="timeout">in millionseconds</param>
        /// <returns></returns>
        public static string PostRequest(string postData, string builderPath, int timeout)
        {
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            byte[] data = encoding.GetBytes(postData);

            UriBuilder builder = CreateUriBuilder();
            builder.Path = builderPath;
            Uri requestUri = builder.Uri;

            // Prepare web request...
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(requestUri);
            ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;
            myRequest.Method = "POST";
            //myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.ContentType = "application/json; charset=utf-8";
            myRequest.ContentLength = data.Length;
            myRequest.CookieContainer = Cookie;
            myRequest.Timeout = timeout;

            string content = string.Empty;

            try
            {
                using (Stream newStream = myRequest.GetRequestStream())
                {
                    newStream.Write(data, 0, data.Length);// Send the data.
                }
                using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse())
                {
                    StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                    content = reader.ReadToEnd();// Get response
                }
            }
            catch (WebException webEx)
            {
                System.Diagnostics.Debug.WriteLine(webEx.ToString());
                //throw;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
                //throw;
            }
            return content;
        }


     public static string GetRequest(string path, string query)
        {
            UriBuilder builder = CreateUriBuilder();
            builder.Path = path;
            builder.Query = query;

            Uri requestUri = builder.Uri;

            HttpWebRequest request = null;
            HttpWebResponse response = null;

            string ret = string.Empty;
            try
            {
                request = (HttpWebRequest)WebRequest.Create(requestUri);
                ServicePointManager.ServerCertificateValidationCallback = ValidateServerCertificate;

                request.CookieContainer = Cookie;

                response = request.GetResponse() as HttpWebResponse;

                using (Stream stream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        ret = reader.ReadToEnd();
                    }
                }
            }
            catch (WebException webEx)
            {
                ret = webEx.Message;
                //throw;
            }
            catch (Exception ex)
            {
                ret = ex.Message;
                //throw;
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }
            return ret;
        }

做完这些。就可以在MainWindow里面愉快地调用WebAPI了。

        private void Button_AddUser_Click(object sender, RoutedEventArgs e)
        {
            User user = new User();
            user.ID = 4;
            user.Platform = Platform.Youtube;
            user.Status = "User";
            user.UserName = "Hello";

            //      myRequest.ContentType = @"application/json; charset=utf-8";//可以发送json字符串作为参数
            //      在Web API端,对应的方法是 AddUser([FromBody]User user)
            //      客户端发送一个对象的Json序列化字符串,在API端可以自动反序列化为具体对象
            string userJsonString = JsonConvert.SerializeObject(user);

            //      myRequest.ContentType = "application/x-www-form-urlencoded";//只能发送&&&&&
            //      在Web API端,对应的方法是Add([FromBody]long id, string userName,int platform,string status)
            StringBuilder sb = new StringBuilder();
            sb.Append(string.Format("id={0}", user.ID));
            sb.Append(string.Format("&platform={0}", 0));
            sb.Append(string.Format("&status={0}", user.Status));
            sb.Append(string.Format("&userName={0}", user.UserName));


            //      在API端的Add方法里面已经用ActionName注解属性强制指明了动作名称为AddUser
            string path = "api/users/AddUser";

            //      myRequest.ContentType = @"application/json; charset=utf-8";//可以发送json字符串作为参数
            //      myRequest.ContentType = "application/x-www-form-urlencoded";//只能发送&&&&&
            //      在WebApiRequest里面因为以及设置了前者,所以这里就发送Json字符串
            string responseString = WebApiRequest.PostRequest(userJsonString, path);

            WriteResult("添加User", responseString);
        }    

         private void Button_UpdateUser_Click(object sender, RoutedEventArgs e)
        {
            //对应的方法是:UpdateUser([FromUri]int id,[FromBody]User user)
            //1,是方法里面从Uri读取的参数
            //user是序列化的Json字符串,需要从body读取
            string path = "api/users/Update/1";

            User user = new User();
            user.ID = 1;
            user.Platform = Platform.Youtube;
            user.Status = "User";
            user.UserName = "Hello";

            string userJsonString = JsonConvert.SerializeObject(user);

            string responseString = WebApiRequest.PostRequest(userJsonString, path);

            WriteResult("更新User", responseString);
        }        

 

        private void Button_GetAllUser_Click(object sender, RoutedEventArgs e)
        {
            string path = "api/users/GetAllUsers";
            string responseString = WebApiRequest.GetRequest(path);

            WriteResult("所有的User", responseString);
        }

        private void Button_GetProductByID_Click(object sender, RoutedEventArgs e)
        {
            int id = 0;
            int.TryParse(TB_UserID.Text, out id);
            string path = string.Format("api/users/GetUserById/{0}", id);
            string responseString = WebApiRequest.GetRequest(path);

            WriteResult("对应ID的User", responseString);
        }    
        private void Button_GetUserByName_Click(object sender, RoutedEventArgs e)
        {
            string path = "api/users/GetUser";
            string query = string.Format("userName={0}", TB_UserName.Text);
            string responseString = WebApiRequest.GetRequest(path,query);

            WriteResult("对应名字的User", responseString);
        }    

 

 

ASP.NET Web API 实例,布布扣,bubuko.com

ASP.NET Web API 实例

标签:style   class   blog   code   http   tar   

原文地址:http://www.cnblogs.com/AlvinLiang/p/3808354.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!