WEBAPI 的简单示例

一、webapi

1.在webapiconfig中移除xml的返回格式,返回格式就自动使用Json格式 
config.Formatters.Remove(config.Formatters.XmlFormatter);

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

namespace WebApplication2
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {

            //移除XML格式,返回值自动就变成json格式
            config.Formatters.Remove(config.Formatters.XmlFormatter);
            // Web API 配置和服务

            //Web API 路由
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

 2.创建一个pig的控制器

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

namespace WebApplication2.Controllers
{
    public class PigController : ApiController
    {
        //GET: api/Pig
        //public IEnumerable<string> Get()
        //{
        //    return new string[] { "大pig", "value2" };
        //}
        public Pig Get()
       {
            Pig pig = new Pig()
            {
                Age = 1,
                Name = "大黄狗"
            };
            return pig;
        }

        //GET: api/Pig/5
        public string Get(int id)
        {
            return "value";
        }

        //POST: api/Pig
        public void Post([FromBody]string value)
        {
        }

        //PUT: api/Pig/5
        public void Put(int id, [FromBody]string value)
        {
        }
        //DELETE: api/Pig/5
        public void Delete(int id)
        {
        }
    }
}

3.发布webapi网站,url=http://localhost:34050/api/Pig

二、客户端调用

新建一个网站,简单一点,就用web窗体,代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    using System.Net;
    public partial class Pig : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //1.0请求的webapi的url:http://localhost:34050/api/Pig
            //1.0构造一个制定url请求对象
            WebRequest request = WebRequest.Create("http://localhost:34050/api/Pig");
            //2.0指定请求的方法为get
            request.Method = "Get";
           //3.0发出请求获取相应对象
            WebResponse response = request.GetResponse();

            //4.0获取相应报文体中的数据
            System.IO.Stream st = response.GetResponseStream();

            //5.0将st转换成字符串
            string resStr = string.Empty;
            using (System.IO.StreamReader sr = new System.IO.StreamReader(st))
            {
                //从当前流的开始位置读至结束位置
                resStr = sr.ReadToEnd();//{"Age":1,"Name":"大黄狗"}
            }

            //6.0将结果绑定到Grid上
            //将json格式的字符串反序列化成集合
            System.Web.Script.Serialization.JavaScriptSerializer jsoner = new System.Web.Script.Serialization.JavaScriptSerializer();
            ResultPig rpig= jsoner.Deserialize<ResultPig>(resStr);
            //如果结果是[{},{}]
            //jsoner.Deserialize<List<ResultPig>>(resStr);
            List<ResultPig> list = new List<ResultPig>() { rpig };
            GridView1.DataSource = list;
            GridView1.DataBind();

            //Response.Write(resStr);
        }
    }
    public class ResultPig
    {
        public int Age { get; set; }
        public string Name { get; set; }
    }
}

  

  

 

posted @ 2019-02-02 10:10  每天进步多一点  阅读(2199)  评论(0编辑  收藏  举报