Use the rest method in asp.net MVC, mvcrest

Source: Internet
Author: User

Use the rest method in asp.net MVC, mvcrest

Preface

Recently, I have implemented the next MVC project. I need to use the rest interface to communicate with applications written in java, including receiving and sending data, then, I will explain how to use it in a practical way.

1. Create a rest Service

First, create an Asp. Net Web application (Visual Studio 2013 is used here and it has built-in Web API2 ).

Select Empty (Empty project) in the template and check WebAPI. Click OK to create an empty WebAPI service.

There is only one empty project and there is no function yet. Before proceeding to the next step, let's take a look at the basic REST operation model, which can be roughly divided into the following four types:

  • POST-create Resource
  • GET-retrieve resources
  • PUT-update resource
  • DELETE-DELETE a resource

A very classic CRUD model. It is very easy to implement such a model in Web API. Just use the Wizard to create a Controller.

 

If you use a traditional wizard, remember to remove the one 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 implement the most 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 at the room end. Let's just talk about the code of 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;} // request url public HttpVerb Method {get; set ;} // Request Method public string ContentType {get; set;} // format type: I use application/json, text/xml, 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 =" Pplication/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 MakeRe Quest () {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 transmitted data is not empty, and the method is post {var encoding = new UTF8Encoding (); var bytes = Encoding. getEncoding ("iso-8859-1 "). getBytes (PostData); // The encoding method is changed as needed, and I'm using the UTF-8 request in the 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 method is put {var encoding = new UTF8Encoding (); var bytes = Encoding. getEncoding ("iso-8859-1 "). getBytes (PostData); // The encoding method is changed as needed, and I'm using the UTF-8 request in the project. contentLength = bytes. length; using (var writeStream = request. getRequestStream () {writeStream. write (bytes, 0, bytes. length) ;}} using (var response = (HttpWebResponse) request. G EtResponse () {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 are commonly used. Of course, you can also add other get: GET post: modify put: Write delete: delete post, PUT, delete }}

2. RestClient usage

With this class, we can easily call other people's rest services, using the following method:

① 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 include parameters

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

③ The most frequently used method

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

Iii. Use in my own projects

1. First, I tested it. I called the get method with parameters in my own rest service. Of course, the parameters I passed here are directly written after the url. The parameter format is string, therefore, the parameters of the get method must be changed to string, so that you can

You can receive the passed parameters. Of course, other applications can also be called. Just give the url to him.

/// <Summary> /// obtain all information of the current user 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 will try the rest service under the java-written application. I have obtained all the user information through the user id I uploaded, of course, I used the caching technology in the project and converted the returned json string into a json object, so that I can operate on it later with linq, for more information about linq to json, refer to my articles on the special topics of linq. The code in my project is sauce:

/// <Summary> /// obtain 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 retrieving user information:" + ex. message );}}

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.