Methods of using rest in asp.net MVC

Time:2021-4-27

preface

Recently, I did the next MVC project. I need to use the rest interface to communicate with applications written in Java, including data receiving and sending. Then I will explain its usage from a practical point of view

1、 Create rest Service

First, create an ASP. Net web application (I use Visual Studio 2013, which has built-in web API 2).

   

Select empty in the template and check webapi. Click OK to create an empty web API service.

   

At this time, there is only one empty project without any function. Before we go to the next step, let’s take a look at the basic operation model of rest, which can be roughly divided into the following four types:

  • Post – create resource
  • Get – Retrieve resources
  • Put – update resource
  • Delete – delete resource

Very classic crud model. It is very simple to implement such a model in the web API. You can directly use the wizard to build a controller

 

  

If you use the traditional guide, remember to remove the 1 after the guide

The default template content is as follows:


   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)
    {
    }
  }

In fact, this has helped us to implement a basic service, so that others can access the methods in our service

2、 Call rest services of other applications

1. Restclient class

For ease of use, we need to encapsulate the rest class on the guest room side

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; }  // The requested URL address 
    public HttpVerb Method { get;  set; }  // Method of request 
    public string ContentType { get;  set; } // Format type: I use application / JSON, text / XML, see the requirements 
    public string PostData { get;  set; }  // The transmitted data, of course, I use the JSON string 

    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) // if the data transferred is not empty and the method is post 
      {
        var encoding = new UTF8Encoding();   
        var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData);// The coding method is changed according to my own needs. I use UTF-8 in my project 
        request.ContentLength = bytes.Length;

        using (var writeStream = request.GetRequestStream())
        {
          writeStream.Write(bytes, 0, bytes.Length);
        }
      }

      if (! String. Isnullorempty (postData) & method = = httpverb. Put) // if the data transferred is not empty and the method is put 
      {
        var encoding = new UTF8Encoding();
        var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData);// The coding method is changed according to my own needs. I use UTF-8 in my project 
        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
  {
    These are the common methods used in get, // method. Of course, you can also add other get: get: Post: modify put: write delete: delete 
    POST,
    PUT,
    DELETE
  }


}

2. Restclient class

With this class, we can easily call other people’s rest services. The usage is as follows:

① , basic call:


var client = new RestClient();
string endPoint = @"http:\myRestService.com\api\";
var client = new RestClient(endPoint);
var json = client.MakeRequest(); 

② If you want to bring in parameters


var json = client.MakeRequest("?param=0");

③ , the most used way


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();

3、 Use in my own projects

1. First of all, I tested it. I called the get method with parameters of my own rest service. Of course, the parameters I passed here are written directly after the URL. The parameter form is string, so the formal parameters of the received get method should also be changed to string, so you can

You can receive the passed parameters. Of course, other people’s applications can also be adjusted. Just give him the URL.

/// <summary>
    ///Get all the information of the current user from the interface
    /// </summary>
    ///< param name = "userid" > User ID < / param >
    ///< returns > JSON object
    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. Next, I’m going to try the rest Service under the application written in Java. I get all the information of the user through the user ID I passed. Of course, I use caching technology in the project, and also convert the returned JSON string into a JSON object, so that I can easily operate it with LINQ, For information about LINQ to JSON, please refer to my articles on LINQ. My code in the project is soy sauce:

/// <summary>
    ///Get all user information from the interface
    /// </summary>
    ///< param name = "userid" > User 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);
          //Insert cache
          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 ("error getting user information): + ex.message];
      }
    }

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.