asp.net MVC下使用rest的方法
最近做了下個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服務了,使用方法如下:
1,基本的調用:
var client = new RestClient();
string endPoint = @"http:\myRestService.comapi";
var client = new RestClient(endPoint);
var json = client.MakeRequest();
2,如果你想帶入參數
var json = client.MakeRequest("?param=0");
3,使用最多的方式
var client = new RestClient();
client.EndPoint = @"http:\myRestService.comapi"; ;
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);
}
}
更多優質內容推薦:
2017優就業就業促進計劃:http://www.ujiuye.com/zt/jycj/?wt.bd=zdy35845tt
中公教育「勤工儉學計劃」,給你一個真正0元學習IT的機會!
http://www.ujiuye.com/zt/qgjx/?wt.bd=zdy35845tt
IT職業教育:http://xue.ujiuye.com/
![](https://pic.pimg.tw/zzuyanan/1488615166-1259157397.png)
![](https://pic.pimg.tw/zzuyanan/1482887990-2595557020.jpg)
※angularjs自定義指令實現分頁插件
※asp.net core 2.0 web api基於JWT自定義策略授權
※WPF的TextBox水印效果詳解
※你該如何拯救,日復一日操心費力的自己?
※程序員的十種形態,句句戳淚點
TAG:IT優就業 |