這篇文章給大家分享的是有關(guān)asp.net MVC下怎么使用rest的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。

一、創(chuàng)建rest服務(wù)
首先創(chuàng)建一個Asp.Net Web應(yīng)用程序(我這里用的是Visual Studio 2013,它已經(jīng)內(nèi)置了Web API2)。

在出來的模板中選擇Empty(空項目),并勾選WebAPI。點(diǎn)擊確定后,就創(chuàng)建了一個空的WebAPI服務(wù)。

此時只有一個空項目,還沒有任何功能,在進(jìn)行下一步之前,首先我們來看一下REST的基本操作模型,大致可以分為如下四種:
POST — 創(chuàng)建資源
GET — 檢索資源
PUT — 更新資源
DELETE — 刪除資源
非常經(jīng)典的CRUD模型。在Web API中實現(xiàn)這樣一個的模型是非常簡單的,直接使用向?qū)Ыㄒ粋€Controller即可


如果用傳統(tǒng)的向?qū)В浀冒严驅(qū)Ш竺娴哪莻€1給去掉:
默認(rèn)的模板內(nèi)容如下:
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)
{
}
}這其實已經(jīng)幫我們實現(xiàn)了一個最基本的服務(wù)了,這樣別人就可以訪問我們的服務(wù)中的方法
二、調(diào)用其它應(yīng)用程序的rest服務(wù)
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; } //傳送的數(shù)據(jù),當(dāng)然了我使用的是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)//如果傳送的數(shù)據(jù)不為空,并且方法是post
{
var encoding = new UTF8Encoding();
var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData);//編碼方式按自己需求進(jìn)行更改,我在項目中使用的是UTF-8
request.ContentLength = bytes.Length;
using (var writeStream = request.GetRequestStream())
{
writeStream.Write(bytes, 0, bytes.Length);
}
}
if (!string.IsNullOrEmpty(PostData) && Method == HttpVerb.PUT)//如果傳送的數(shù)據(jù)不為空,并且方法是put
{
var encoding = new UTF8Encoding();
var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData);//編碼方式按自己需求進(jìn)行更改,我在項目中使用的是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 常用的就這幾樣,當(dāng)然你也可以添加其他的 get:獲取 post:修改 put:寫入 delete:刪除
POST,
PUT,
DELETE
}
}2、RestClient類使用
有了這個類后我們就很方便的去調(diào)用別人的rest服務(wù)了,使用方法如下:
①,基本的調(diào)用:
var client = new RestClient(); string endPoint = @"http:\\myRestService.com\api\"; var client = new RestClient(endPoint); var json = client.MakeRequest();
②,如果你想帶入?yún)?shù)
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、首先我測試了一下,我調(diào)用我自己的rest服務(wù)的帶參的get方法,當(dāng)然我這里傳的參數(shù)直接寫在url的后面在,參數(shù)形式是string,所以接收的get方法的形參也要改成string,這樣你就
可以接收到傳過去的參數(shù)了。當(dāng)然別人應(yīng)用程序也是可以調(diào)的。只要把url給他就行了。
/// <summary>
/// 從接口中獲取當(dāng)前用戶所有信息
/// </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寫的應(yīng)用程序下的rest服務(wù)了,我通過我傳過去的用戶ID獲取到了用戶的所有信息,當(dāng)然我在項目中使用了緩存技術(shù),還將返回回來的json字符串轉(zhuǎn)換成了json對象,以便我后面好用linq對其進(jìn)行操作,關(guān)于linq to json 可以參考我的linq專題相關(guān)文章 ,我在項目中的代碼是醬子的:
/// <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);
}
}感謝各位的閱讀!關(guān)于“asp.net MVC下怎么使用rest”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學(xué)到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
分享標(biāo)題:asp.netMVC下怎么使用rest-創(chuàng)新互聯(lián)
URL標(biāo)題:http://www.chinadenli.net/article8/djhhop.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供做網(wǎng)站、App設(shè)計、企業(yè)網(wǎng)站制作、外貿(mào)建站、App開發(fā)、企業(yè)建站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容