国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > .NET > 正文

asp.net MVC下使用rest的方法

2024-07-10 12:54:33
字體:
來源:轉載
供稿:網友

我們都知道軟件開發后要通過網絡進行推廣,使大家愛都知道有這款軟件,這是很正常的做法,下面就讓錯新技術頻道小編為您介紹asp.net MVC下使用rest的方法吧!

一、創建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);      }    }

上文就是關于asp.net MVC下使用rest的方法介紹,如果你感覺有幫助就收藏js.VeVb.com吧,錯新技術頻道會給你帶來最專業的知識點。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 莱西市| 任丘市| 进贤县| 当雄县| 乌拉特前旗| 红原县| 集贤县| 含山县| 伽师县| 闵行区| 莱芜市| 衡阳市| 石渠县| 凤翔县| 陆良县| 宾阳县| 达州市| 宝应县| 综艺| 习水县| 莱芜市| 两当县| 焦作市| 绥德县| 额敏县| 武安市| 信宜市| 托里县| 洛扎县| 秀山| 高平市| 眉山市| 横峰县| 旺苍县| 阳江市| 正阳县| 靖边县| 尼勒克县| 屯留县| 锡林浩特市| 天等县|