WebApi简单使用

一、建立一个WebApi项目

  WebApi项目的文件和MVC的基本项目内容差不多,都有Models View Controller等,区别在于WebApi的控制器继承的不是Controller类,而是ApiController。另外控制器中默认的Action名称与HttpMethod同名或者以Get、Post开头,不支持使用其他名称。

例如:

    public class ValuesController : ApiController
    {
        public List<Pig> Get(int id)
        {
            return new List<Pig>()
            {
                new Pig(){Name="1号猪",Age=12},
                new Pig(){Name="2号猪",Age=13}
            };
        }
    }


    //Model必须提供public的属性,用于json或xml反序列化时的赋值
    public class Pig
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

二、WebApi的请求

  建立一个MVC基本项目,在控制器中请求WebApi,返回的是json格式的数据。

        public ActionResult Index()
        {
            //请求webapi
            WebRequest request = HttpWebRequest.Create("http://localhost:30078/api/values/get/1");
            request.Method = "get";

            WebResponse response = request.GetResponse();
            Stream stream = response.GetResponseStream();
            string res = "";
            using (StreamReader sr = new StreamReader(stream))
            {
                res = sr.ReadToEnd();
            }
            return Content(res);
        }
原文地址:https://www.cnblogs.com/miaoying/p/5481361.html