Describes how to use rest under ASP.

Source: Internet
Author: User
This article mainly introduces the method of using rest under ASP., small series feel very good, and now share to everyone, but also for everyone to do a reference. Let's take a look at it with a little knitting.

Objective

I have recently done the next MVC project and need to use the rest interface to communicate with the Java-written application, including the data receiving and sending, then I will use a practical perspective to fully explain how it is used

First, create a rest service

Start by creating an ASP. NET Web application (I'm using Visual Studio 2013, which has built-in web API2).

In the Out template select Empty (empty project), and tick webapi. When you click OK, an empty WEBAPI service is created.

There is only one empty project at this time, there is no function, before the next step, we first look at the rest of the basic operating model, can be divided into the following four kinds:

    • Post-Creating a Resource

    • Get-Retrieving resources

    • put-Updating resources

    • delete-Deleting resources

A very classic crud model. The implementation of such a model in the Web API is straightforward, and a controller can be built directly using the wizard.

If you use a traditional wizard, remember to remove the 1 behind the wizard:

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

This has actually helped us to achieve a basic service, so that others can access our services in the method

Second, rest services that invoke other applications

1, Restclient class

For ease of use, we need to encapsulate the rest class on the room side, without saying that we are directly on the code for this class:


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;}  Requested URL address public httpverb Method {get; set;} Requested method public string ContentType {get; set;}//format type: I'm using application/json,text/xml. What to use, see Requirements public string Post  Data {get; set;}      Transmitted data, of course I am using 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 = Endpoin      T      Method = method;      ContentType = ContentType;    PostData = PostData;    } public string MakeRequest () {return makerequest (""); } public string MakeRequest (string parameters) {var request = (HttpWebRequest) webrequest.create (EndPoint + par      Ameters); Request.      Method = Method.tostring (); Request.            ContentType = ContentType; if (!string. IsNullOrEmpty (postdata) && method = = httpverb.post)//If the transmitted data is not empty, and the methods are POST {var encoding = new Utf8en           Coding (); var bytes = encoding.getencoding ("Iso-8859-1"). GetBytes (postdata);//The encoding is changed according to your own needs, and I use UTF-8 request in my project. contentlength = bytes.        Length; using (var writestream = Request.     GetRequestStream ())   {writestream.write (bytes, 0, bytes.        Length); }} if (!string. IsNullOrEmpty (postdata) && method = = httpverb.put)//If the transmitted data is not empty, and the methods are PUT {var encoding = new Utf8enco        Ding (); var bytes = encoding.getencoding ("Iso-8859-1"). GetBytes (postdata);//The encoding is changed according to your own needs, and I use UTF-8 request in my project. 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 commonly used on these, of course you can also add other get: Get post: Modify put: Write Delete: Delete post, PUT, DELETE}}

2, Restclient class use

With this class we are very convenient to call other people's rest services, using the following methods:

①, basic invocation:


var client = new Restclient (), String endPoint = @ "http:\\myrestservice.com\api\"; var client = new Restclient (endPoint); VA R 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 ();

Third, the use of my own project

1, first I tested, I call my own rest service with the parameter get method, of course, I pass the parameter is written directly behind the URL, the Parameter form is a string, so the received get method of the formal parameters to be changed to a string, so you

You can receive the parameters passed in the past. Of course other people's applications are also adjustable. Just give him the URL.


<summary>////    Get all current user information from the interface///</summary>//    <param name= "userId" > User id</ Param>    //<returns>json Object </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. Next, I'm going to try out the rest service under the Java-written application, I get all the user's information through my pass-through user ID, of course I use caching technology in my project, and I convert the returned JSON string into a JSON object. So that I can work with LINQ in the back, and about LINQ to JSON, refer to my LINQ topic related articles, my Code in the project is the sauce:


<summary>///Receive all user information from the interface///</summary>//<param name= "userId" > User id</param>// /<returns></returns> public static Jobject Cacheuser () {try {string currentUser = Ge        Tcurrentuserid (); 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 (+), Tim        Espan.zero);  } return (Jobject) HttpRuntime.Cache.Get ("user$" + Getcurrentuserid ());    } catch (Exception ex) {throw new ApplicationException ("Error getting User information:" +ex.      Message); }    }
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.