媒介
近来做了下个MVC的项目,须要用到rest接口,与java写的应用程序通讯,包含数据的吸收和发送,那末我将用有用的角度来周全的解说一下它的运用要领
一、建立rest效劳
起首建立一个Asp.Net Web应用程序(我这里用的是Visual Studio 2013,它已内置了Web API2)。
在出来的模板中挑选Empty(空项目),并勾选WebAPI。点击肯定后,就建立了一个空的WebAPI效劳。
此时只要一个空项目,还没有任何功用,在举行下一步之前,起首我们来看一下REST的基础操纵模子,大抵能够分为以下四种:
POST — 建立资本
GET — 检索资本
PUT — 更新资本
DELETE — 删除资本
异常典范的CRUD模子。在Web API中完成如许一个的模子是异常简朴的,直接运用导游建一个Controller即可
假如用传统的导游,记得把导游背面的谁人1给去掉:
默许的模板内容以下:
public class ValuesController : ApiController { // GET api/<controller> publicIEnumerable<string> Get() { returnnewstring[] { "value1", "value2" }; } // GET api/<controller>/5 publicstring Get(int id) { return"value"; } // POST api/<controller> publicvoid Post([FromBody]string value) { } // PUT api/<controller>/5 publicvoid Put(int id, [FromBody]string value) { } // DELETE api/<controller>/5 publicvoid Delete(int id) { } }
这实在已帮我们完成了一个最基础的效劳了,如许他人就能够接见我们的效劳中的要领
二、挪用别的应用程序的rest效劳
1、RestClient类
为了便于运用,我们须要封装客房端的rest类,话不多说,我们直接上这个类的代码:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Web; namespace OilDigital.A2_A27.Web { public class RestClient { public string EndPoint { get; set; } //要求的url地点 public HttpVerb Method { get; set; } //要求的要领 public string ContentType { get; set; } //花样范例:我用的是application/json,text/xml细致运用什么,看需求吧 public string PostData { get; set; } //传送的数据,固然了我运用的是json字符串 public RestClient() { EndPoint = ""; Method = HttpVerb.GET; ContentType = "application/x-www-form-urlencoded"; PostData = ""; } public RestClient(string endpoint) { EndPoint = endpoint; Method = HttpVerb.GET; ContentType = "application/json"; PostData = ""; } public RestClient(string endpoint, HttpVerb method) { EndPoint = endpoint; Method = method; ContentType = "application/json"; PostData = ""; } public RestClient(string endpoint, HttpVerb method, string postData) { EndPoint = endpoint; Method = method; ContentType = "application/json"; PostData = postData; } public RestClient(string endpoint, HttpVerb method, string postData, string contentType) { EndPoint = endpoint; Method = method; ContentType = contentType; PostData = postData; } public string MakeRequest() { return MakeRequest(""); } public string MakeRequest(string parameters) { var request = (HttpWebRequest)WebRequest.Create(EndPoint + parameters); request.Method = Method.ToString(); request.ContentType = ContentType; if (!string.IsNullOrEmpty(PostData) && Method == HttpVerb.POST)//假如传送的数据不为空,而且要领是post { var encoding = new UTF8Encoding(); var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData);//编码体式格局按本身需求举行变动,我在项目中运用的是UTF-8 request.ContentLength = bytes.Length; using (var writeStream = request.GetRequestStream()) { writeStream.Write(bytes, 0, bytes.Length); } } if (!string.IsNullOrEmpty(PostData) && Method == HttpVerb.PUT)//假如传送的数据不为空,而且要领是put { var encoding = new UTF8Encoding(); var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData);//编码体式格局按本身需求举行变动,我在项目中运用的是UTF-8 request.ContentLength = bytes.Length; using (var writeStream = request.GetRequestStream()) { writeStream.Write(bytes, 0, bytes.Length); } } using (var response = (HttpWebResponse)request.GetResponse()) { var responseValue = string.Empty; if (response.StatusCode != HttpStatusCode.OK) { var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode); throw new ApplicationException(message); } // grab the response using (var responseStream = response.GetResponseStream()) { if (responseStream != null) using (var reader = new StreamReader(responseStream)) { responseValue = reader.ReadToEnd(); } } return responseValue; } } } public enum HttpVerb { GET, //method 经常使用的就这几样,固然你也能够增加其他的 get:猎取 post:修正 put:写入 delete:删除 POST, PUT, DELETE } }
2、RestClient类运用
有了这个类后我们就很轻易的去挪用他人的rest效劳了,运用要领以下:
①,基础的挪用:
var client = new RestClient(); string endPoint = @"http:\\myRestService.com\api\"; var client = new RestClient(endPoint); var json = client.MakeRequest();
②,假如你想带入参数
var json = client.MakeRequest("?param=0");
③,运用最多的体式格局
var client = new RestClient(); client.EndPoint = @"http:\\myRestService.com\api\"; ; client.ContentType = "application/json"; client.Method = HttpVerb.POST; client.PostData = "{postData: value}"; var json = client.MakeRequest();
三、我本身项目中的运用
1、起首我测试了一下,我挪用我本身的rest效劳的带参的get要领,固然我这里传的参数直接写在url的背面在,参数情势是string,所以吸收的get要领的形参也要改成string,如许你就
能够吸收到传过去的参数了。固然他人应用程序也是能够调的。只要把url给他就好了。
/// <summary> /// 从接口中猎取当前用户一切信息 /// </summary> /// <param name="userId">用户ID</param> /// <returns>json对象</returns> public string GetCurrentUserInfo() { string userId = GetCurrentUserId(); string endPoint = "http://localhost:100/Api/RestService/"+userId; var client = new RestClient(endPoint); var userInfo = client.MakeRequest(); return userInfo; }
2、接下来,我要最先试用java写的应用程序下的rest效劳了,我经由过程我传过去的用户ID猎取到了用户的一切信息,固然我在项目中运用了缓存手艺,还将返回返来的json字符串转换成了json对象,以便我背面好用linq对其举行操纵,关于linq to json 能够参考我的linq专题相干文章 ,我在项目中的代码是酱子的:
/// <summary> /// 从接口中猎取用户一切信息 /// </summary> /// <param name="userId">用户ID</param> /// <returns></returns> public static JObject CacheUser() { try { string currentUser = GetCurrentUserId(); if (HttpRuntime.Cache.Get("user$" + GetCurrentUserId()) == null) { string endPoint = "http://66.66.66.666:6666/DASBASE/restServices/dataCollectionService/getUserPermissions"; string postData = "jsonData={\"userCode\": \"kfry\",\"systemId\": \"1E1A7AC94BFC41D4BEBED8942EB69689\"}"; var client = new RestClient(endPoint, HttpVerb.POST, postData, "application/x-www-form-urlencoded"); var u = client.MakeRequest(); JObject userInfo = JObject.Parse(u); //插进去缓存 HttpRuntime.Cache.Insert("user$" + currentUser, userInfo, null, System.DateTime.UtcNow.AddMinutes(30), TimeSpan.Zero); } return (JObject)HttpRuntime.Cache.Get("user$" + GetCurrentUserId()); } catch (Exception ex) { throw new ApplicationException("猎取用户信息失足:"+ex.Message); } }
以上就是Rest在asp.net MVC下运用的要领引见的细致内容,更多请关注ki4网别的相干文章!