溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Rest在asp.net MVC下如何使用

發(fā)布時間:2020-04-15 10:01:07 來源:億速云 閱讀:454 作者:小新 欄目:編程語言

這篇文章主要為大家詳細介紹了Rest在asp.net MVC下的使用方法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下。

前言

最近做了下個MVC的項目,需要用到rest接口,與java寫的應(yīng)用程序通信,包括數(shù)據(jù)的接收和發(fā)送,那么我將用實用的角度來全面的講解一下它的使用方法

一、創(chuàng)建rest服務(wù)

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

Rest在asp.net MVC下如何使用  

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

Rest在asp.net MVC下如何使用  

此時只有一個空項目,還沒有任何功能,在進行下一步之前,首先我們來看一下REST的基本操作模型,大致可以分為如下四種:

  • POST — 創(chuàng)建資源

  • GET — 檢索資源

  • PUT — 更新資源

  • DELETE — 刪除資源

非常經(jīng)典的CRUD模型。在Web API中實現(xiàn)這樣一個的模型是非常簡單的,直接使用向?qū)Ыㄒ粋€Controller即可

Rest在asp.net MVC下如何使用

Rest在asp.net MVC下如何使用  

如果用傳統(tǒng)的向?qū)?,記得把向?qū)Ш竺娴哪莻€1給去掉:

默認的模板內(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ù),當然了我使用的是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);//編碼方式按自己需求進行更改,我在項目中使用的是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);//編碼方式按自己需求進行更改,我在項目中使用的是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類使用

有了這個類后我們就很方便的去調(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方法,當然我這里傳的參數(shù)直接寫在url的后面在,參數(shù)形式是string,所以接收的get方法的形參也要改成string,這樣你就

可以接收到傳過去的參數(shù)了。當然別人應(yīng)用程序也是可以調(diào)的。只要把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寫的應(yīng)用程序下的rest服務(wù)了,我通過我傳過去的用戶ID獲取到了用戶的所有信息,當然我在項目中使用了緩存技術(shù),還將返回回來的json字符串轉(zhuǎn)換成了json對象,以便我后面好用linq對其進行操作,關(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)于Rest在asp.net MVC下如何使用就分享到這里了,當然并不止以上和大家分析的辦法,不過小編可以保證其準確性是絕對沒問題的。希望以上內(nèi)容可以對大家有一定的參考價值,可以學(xué)以致用。如果喜歡本篇文章,不妨把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI