WCF 它利用TCP、HTTP、MSMQ等传输协议构建“契约先行”的服务。WCF最初为基于SOAP的服务而设计[xml],繁琐、冗余、慢、沉重
WebApi 基于http协议,轻量级的,支持URL路由,透过用户熟悉的MVC风格路由语义,生成干净的URL
新建webapi项目就不说了,webapi充当服务,其实也就是一个类似于mvc的项目 public class DongController : ApiController { //Us_User自己新建的一个实体类 public List<Us_User> GetUserId(int k) { var list = new List<Us_User>(); for (int i = 0; i < k; i++) { var model = new Us_User { Id = i, Age = i * 5, Name = "你好" + i, Sex = "男" + i }; list.Add(model); } return list; } [HttpPost] //[FromBody]它指拿HttpRequestMessage里参数 public IList<Us_User> PostUserName([FromBody]ParamModel obj) { var list = new List<Us_User>(); for (int i = 0; i < obj.Index; i++) { var model = new Us_User { Id = i, Age = i * 5, Name = obj.Phone + i, Sex = obj.UName + i }; list.Add(model); } return list; } }
另一个项目开始调用 //Get方式 public ActionResult Index() { HttpClient client = new HttpClient(); var responseJson = client.GetAsync("http://localhost:40821/api/Dong/GetUserId?k=9").Result.Content.ReadAsStringAsync().Result; var list = JsonConvert.DeserializeObject<List<Us_User>>(responseJson); return View(); }
//Post方式 public void GetName(string userName) { var json = JsonConvert.SerializeObject(new { Index = 10, Num = 20, Phone = "15210225315", UName = "hehe" }); HttpContent httpContent = new StringContent(json); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); HttpClient client = new HttpClient(); var responseJson = client.PostAsync("http://localhost:40821/api/Dong/PostUserName", httpContent).Result.Content.ReadAsStringAsync().Result; var list = JsonConvert.DeserializeObject<List<Us_User>>(responseJson); }
使用put方式时出现不支持
设置WebApi跨域 ,WebApi的web.config中加入下面跨域跨域设置即可
<system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*" /> <add name="Access-Control-Allow-Headers" value="Content-Type" /> <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" /> </customHeaders> </httpProtocol>