Server and client interaction based on ASP. NET MVC (iii) Client request response

Source: Internet
Author: User
Tags script tag

First, analysis

The four main methods of HTTP request in the WEB API (GET, PUT, POST, DELETE) are mapped to curd operations in the following ways:

    • Get is used to get the presentation of the URI resource, and the get operation should not have any effect on the server, select query for data collection;
    • Put is used to update a resource on a URI, and if the server allows it, put can also be used to create a new resource for the relevant insert insert operation;
    • POST is used to create a new resource, and the server creates an object on the specified URI, returning the address of the new resource as part of the response message for the relevant update;
    • Delete is used to delete the specified URI resource. The associated delete operation is based on the input parameters.

In addition to using the old WebClient, HttpWebRequest to access the server API, the client can also operate with the new HttpClient category, which is contained in the. Net Framework 4.5 Under the System.Net.Http namespace, the HttpClient category generally needs to be available on the. Net Framework 4.5 and can be used with NuGet search Microsoft.net.http,nuget with 4.0 available The installation package.

HttpClient class in the delivery of information is usually through the multi-layer Handler, the information layer, the server receives request requests, and then makes the reply return information, this process is also known as delegating Handler.

on the Web side, you can also get data through the Jqery Ajax asynchronous request Web API.

    • Data (MAP): (optional parameter) Key/value data sent to the server.
    • URL (String): The URL address of the requested HTML page.
    • dataType: The value returned by the server is parsed according to this data type.
    • success: called after the request is made, the returned data is passed in, and the string containing the success code.

Data types for dataType

• "XML": Returns an XML document that can be processed using JQuery.
• HTML: Returns plain text HTML information, and the included script tag is executed when the DOM is inserted.
• "Script": Returns plain text JavaScript code. Results are not automatically cached. Unless the "cache" parameter is set. Note: On remote requests (not in the same domain), all POST requests are converted to GET requests. (because the script tag of the DOM will be used to load)
• "JSON": Returns the JSON data.
• "JSONP": Jsonp format. When calling a function using JSONP form, such as "myurl?callback=?" JQuery is automatically replaced? is the correct function name to execute the callback function.
• "Text": Returns a plain text string

Second, scene simulation C # application console analog access request get data

Use HttpClient's postasync to access the token obtained from the server GET request, access the data with the token, and then return the data.

1   Public class Token 2         {3             [Jsonproperty ("access_token")]4 public             stringgetset;} 5         }
View Code

1  Static voidMain (string[] args)2         {3             Const stringURL ="http://localhost:14259/";4             varClient =NewHttpClient ();5             varDict =Newsorteddictionary<string,string>();6Dict. ADD ("client_id","Xiangzhang");7Dict. ADD ("Client_secret","212");8Dict. ADD ("Grant_type","client_credentials");9             //var rst = await (@ "http://"+ Request.RequestUri.Authority + @"/token "). Posturlencodedasync (dict). Receivejson<token> ();Ten             //Console.WriteLine (_httpclient.postasync ("/token", new Formurlencodedcontent (parameters)). Result.Content.ReadAsStringAsync (). Result); One             varRST = client. Postasync (URL +"token",Newformurlencodedcontent (dict)). Result.Content.ReadAsStringAsync (). Result; A             varobj = jsonconvert.deserializeobject<token>(RST); -Client. Defaultrequestheaders.authorization =NewAuthenticationheadervalue ("Bearer", obj. Accesstoken); -RST = client. Getstringasync (URL +"api/values"). Result; the Console.WriteLine (RST); - console.readline (); -}
View Codeasp jqery Ajax Asynchronous Request

1 var apiservicebaseuri = "http://localhost:14259/";

1 $.ajax ({2Url:apiservicebaseuri + "Api/values",3Type: "Get",4DataType: "JSON",5 headers: {6"Authorization": "Bearer" +Accesstoken7                     },8Successfunction(data) {9                         Ten$ ("#h11"). text (data); One                     }, AErrorfunction () { -Alert ("Get Data Failed"); -                     } the});
GET Requestput request
1 $.ajax ({2Type"Post",3Url:apiservicebaseuri +"token",4Data: {client_id:"Irving", Client_secret:"123456", Grant_type:"client_credentials" },5DataType:"JSON",6 success:function (data) {7Accesstoken =Data.access_token;;8 $.ajax ({9Type"Post",TenUrl:'/home/getaccesstoken', One data: {Token:accesstoken}, ADataType:"JSON" -                         }); -                     }, the error:function () { -Alert"Get Token arror!"); -                     } -});
POST Request

Server and client interaction based on ASP. NET MVC (iii) Client request response

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.