MVC |Web API | HttpClent

来源:互联网 发布:播放类软件 编辑:程序博客网 时间:2024/06/06 01:18

两种Web服务

一》SOAP风格,基于方法,产品是:WebServices(它主要针对方法进行逻辑操作,所以它是逻辑层面上的东西)

一》REST风格,基于资源,产品是:WebAPI (它的应用场景是:主要是针对数据库中的表进行增删改查操作,而不是其他的逻辑处理,所以说它是数据层面上的东西)

这两种Web服务都可以返回json,xml类型的数据

对于数据的增,删,改,查,提供相对的资源操作,按照请求的类型进行相应处理,主要包括Get(查),Post(增),Put(改),Delete(删),这些都是Http协议支持的请求方式。

使用方法:2种请求类型

第一种请求方式:使用Jquery异步中的dataType指定请求类型(Get,Post,Put,Delete)缺点是不支持跨域操作,所以它只能完成对本地的访问。

第二种请求方式:使用HttpClient对象,优点是支持从跨域操作,在其他的网站都可以发起请求,所以它可以完成远程的访问


WebApi 接口返回值不困惑:返回值类型详解[重要]

WebApi接口传参不再困惑:传参详解[重要]

新建一个WebApi

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 UserInfoController : ApiController    {        // 查 api/userinfo        public IHttpActionResult Get([FromUri]T_UserInfo u) //如果采用Get方式,使用复杂类型接收的话,需要在参数前面加[FromUri]        {            salesEntities db = new salesEntities();                        var list = db.T_UserInfo.ToList();            return Json<List<T_UserInfo>>(list);        }        // 查 api/userinfo/5        //public List<T_UserInfo> Get([ModelBinder(typeof(UserInfoBinding))] T_UserInfo u)               //{        //    salesEntities db = new salesEntities();        //    var list = db.Set<T_UserInfo>().Where(r => true);        //    if (u.Id != 0)        //    {        //        list = list.Where(r => r.Id > u.Id);        //    }        //    if (!string.IsNullOrEmpty(u.Name))        //    {        //        list = list.Where(r => r.Name == u.Name);        //    }        //    return list.ToList();        //}        // 增 (建议使用dynamic类型做参数的接收类型)        [HttpPost]        public int AddData(dynamic obj) //obj的值是一个Josn对象 {"Id": 4, "Name": "张三" }        {            var id = obj.Id.Value;            var name = obj.Name.Value;            T_UserInfo u = new T_UserInfo()            {                Id = id,                Name = name            };                                   salesEntities db = new salesEntities();            db.Set<T_UserInfo>().Add(u);            return db.SaveChanges();                   }        // 改 (建议使用dynamic类型做参数的接收类型)        public void Put(dynamic obj) //obj的值是一个Josn对象  {"Id": 4, "Name": "张三" }        {            var id = obj.Id.Value;            var name = obj.Name.Value;        }        // 删 api/userinfo/5        [HttpDelete]        public IHttpActionResult Delete(int id)        {            salesEntities db = new salesEntities();            if (id != 0)            {                var entity = db.T_UserInfo.FirstOrDefault(r => r.Id == id);                db.T_UserInfo.Remove(entity);                db.SaveChanges();            }            return Ok<string>("OK"); //直接返回一个字符串OK             //return Ok(); //如果返回Ok(),就表示不向客户端返回任何信息,只告诉客户端请求成功。        }    }}

在同域下使用js的异步请求WebApi

 (新建一个HtmlPage1.html静态页面,在里面写js异步)

<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>    <title></title>    <script src="Scripts/jquery-1.10.2.js"></script></head><body></body></html><script type="text/javascript">    $(function () {        DeleteItem();    })    function GetList() {        $.ajax({            url: "http://localhost:8307/api/UserInfo",            type: "Get",            data:{Id:1,Name:"张三"},            contentType: "application/json; charset=utf-8", //一定要加上这个            dataType: "json",                       success: function (data, textStatus) {                alert(data[0].Name);            }        })    }    function GetItem() {        $.ajax({            url: "http://localhost:8307/api/UserInfo/",            type: "Get",            data: { Id: 1, Name: '张三' },            contentType: "application/json; charset=utf-8", //一定要加上这个            dataType: "json",            success: function (data, textStatus) {                alert(data[0].Name);            }        })    }    function AddItem() { //如果是Post传递参数,建议使用JSON.stringify({ Id: 4, Name: '张三' })这种方式传值        $.ajax({            url: "http://localhost:8307/api/UserInfo/AddData",            type: "Post",            data: JSON.stringify({ Id: 4, Name: '张三' }),            contentType: "application/json; charset=utf-8", //一定要加上这个            dataType: "json",            success: function (data, textStatus) {                alert(data[0].Name);            }        })    }       function EditItem() { //如果是Put传递参数,建议使用JSON.stringify({ Id: 4, Name: '张三' })这种方式传值        $.ajax({            url: "http://localhost:8307/api/UserInfo",            type: "Put",            data: JSON.stringify({ Id: 3, Name: '张三' }),            contentType: "application/json; charset=utf-8", //一定要加上这个            dataType: "json",            success: function (data, textStatus) {                alert(data[0].Name);            }        })    }    function DeleteItem() { //如果是Delete传递参数,就只要在url后面跟参数就可以了        $.ajax({            url: "http://localhost:8307/api/UserInfo/13",            type: "Delete",            data: { Id: 2 },            contentType: "application/json; charset=utf-8", //一定要加上这个            dataType: "json",            success: function (data, textStatus) {                alert(data[0].Name);            }        })    }   </script>


使用HttpClent来请求

Get请求

public class HomeController : Controller{    public ActionResult Index()    {        //Get请求----------                //客户端对象的创建与初始化        HttpClient client = new HttpClient();        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));        //执行Post或者Get操作        //client.GetAsync 异步调用Get请求        //client.PostAsync 异步调用Post请求        //client.DeleteAsync 异步调用Delete请求        //client.PutAsync 异步调用Put请求        HttpResponseMessage response = client.GetAsync("http://localhost:8307/api/userinfo").Result;        var list = response.Content.ReadAsAsync<List<T_UserInfo>>().Result;                return View();    }}

Post请求

public class HomeController : Controller{    public ActionResult Index()    {        //Post请求----------                string url = "http://localhost:8307/api/userinfo/AddData";string strContent = @"{""Id"":22,""Name"":""刘雅林""}";        HttpClient client = new HttpClient();        HttpContent content = new StringContent(strContent);        //content.Headers.ContentType = new MediaTypeHeaderValue("application/json");        //var resultInt = client.PostAsync(serviceRequest, content).ContinueWith(        //     (requestTask) =>        //     {        //         HttpResponseMessage response = requestTask.Result;        //         response.EnsureSuccessStatusCode();        //         response.Content.ReadAsAsync<int>().ContinueWith(        //             (readTask) =>        //             {        //                 return readTask.Result;        //             });        //     });        content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");        HttpResponseMessage response = client.PostAsync(url, content).Result;        var resultInt = response.Content.ReadAsAsync<int>().Result;               return View();    }}


Delete请求

public class HomeController : Controller{    public ActionResult Index()    {            //Delete请求----------            string url = "http://localhost:8307/api/userinfo/12";            string strContent = @"{""age"":25,""Name"":""刘雅林""}";            HttpClient client = new HttpClient();            HttpContent content = new StringContent(strContent);            content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");            HttpResponseMessage response = client.DeleteAsync(url).Result;            var resultInt = response.Content.ReadAsAsync<string>().Result; //返回OK                return View();    }}

使用HttpWebRequest请求API

public class HomeController : Controller{    public ActionResult Index()    {        string url = "http://localhost:8307/api/userInfo";        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;        request.Method = "Get";        string resultStr = string.Empty;        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)        {            using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))            {                resultStr = sr.ReadToEnd();            }        }        //将json转对象        List<T_UserInfo> list = Newtonsoft.Json.JsonConvert.DeserializeObjectAsync<List<T_UserInfo>>(resultStr).Result;        return View();    }}


0 0
原创粉丝点击