這篇文章主要為大家詳細介紹了Rest在asp.net MVC下的使用方法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下。
前言
最近做了下個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下如何使用就分享到這里了,當然并不止以上和大家分析的辦法,不過小編可以保證其準確性是絕對沒問題的。希望以上內容可以對大家有一定的參考價值,可以學以致用。如果喜歡本篇文章,不妨把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。