Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

WebApi interface-how to call the webapi interface in an application

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)06/01 Report--

Simply make a webapi (query + add) interface

First of all, we need to have a webapi interface project. Here, I use the previous WebApi interface-response to output xml and json articles to build the test cases of this article. Here, we create a new DbData data source class, which is mainly used to store data and provide query list data and add data methods. The specific code is as follows:

1 public class DbData 2 {3 public static DbData Current 4 {5 get 6 {7 var key = "dbKey"; 8 var db = CallContext.GetData (key) as DbData; 9 if (db = = null) 10 {11 db = new DbData () 12 CallContext.SetData (key, db); 13} 14 return db 15} 16} 17 18 19 private static List students = new List () {20 new MoStudent {Id = 1, Name = "Xiao 1", Sex = true, Birthday= Convert.ToDateTime ("1991-05-31")}, 21 new MoStudent {Id = 2, Name = "Xiao 2", Sex = false, Birthday= Convert.ToDateTime ("1991-05-31")}, 22 new MoStudent {Id = 3 Name = "Xiao 3", Sex = false, Birthday= Convert.ToDateTime ("1991-05-31")}, 23 new MoStudent {Id = 4, Name = "Xiao 4", Sex = true, Birthday= Convert.ToDateTime ("1991-05-31")} 24} 25 26 public List GetAll () 27 {28 return students;29} 30 31 public bool Save (MoStudent moStudent) 32 {33 moStudent.Id = students.Max (b = > b.Id) + 1 return true;36 34 students.Add (moStudent); 35 return true;36} 37}

Then, you need to add the call data source class DbData to the ValuesController.cs file, code: private DbData db = DbData.Current Here, we use the Current attribute in the DbData class to obtain the instantiated object of DbData. The advantage of this is to uniformly manage the instance of the calling class, because after we create an operation class, it may be called in different files or in different businesses. If you want to call its internal method, you need to use new an object, so it is very cumbersome to new many times in the place where you use it. And it can't be maintained. Of course, the DbData here is a simple test case, and no factory, abstract and other designs are used to deal with instances such as declarations (you can ignore it).

All right, let's create a method GetAllStudents01_2 for obtaining student list information and a method AddStudent for adding student information in ValuesController, and then fill in the internal code such as:

1 private DbData db = DbData.Current; 2 3 [Route ("all01_2")] 4 [AcceptVerbs ("POST", "GET")] 5 public HttpResponseMessage GetAllStudents01_2 () 6 {7 var students = db.GetAll (); 8 return Request.CreateResponse (HttpStatusCode.OK, students) 9} 10 11 [Route ("add")] 12 [HttpPost] 13 public HttpResponseMessage AddStudent (MoStudent moStudent) 14 {15 var httpStatus = HttpStatusCode.OK;16 if (ModelState.IsValid) 17 {18 var isfalse = db.Save (moStudent); 19} 20 return Request.CreateResponse (httpStatus, moStudent); 21}

You can take a look at the parameters or return information of the two methods without more processing. After creating the api API code, let's test and visit the student list API, such as http://localhost:1001/s/all01_2, and get the result diagram:

The data returned is in json format. The data format of this article is json, which is also one of the most commonly used return data formats.

How to call api Interface in MVC Code

First, create a mvc project by reading the article WebApi-routing, then add two Action methods, Index (student list) and Add (add student information), to the HomeController.cs file, and fill in the code such as:

1 public class HomeController: Controller 2 {3 4 public async Task Index () 5 {6 7 var searchData = new MoStudent (); 8 / / query condition 9 10 var webapiUrl = "http://localhost:1001/s/all01_2";11 var httpResponseMsg = new HttpResponseMessage () 12 13 using (var httpClient = new HttpClient ()) 14 {15 httpResponseMsg = await httpClient.PostAsync (webapiUrl, searchData, new System.Net.Http.Formatting.JsonMediaTypeFormatter ()); 16} 17 var students = httpResponseMsg.Content.ReadAsAsync () .Result;18 19 return View (students) 20} 21 22 [HttpGet] 23 public ActionResult Add () 24 {25 26 return View (); 27} 28 29 [HttpPost] 30 public async Task Add (MoStudent model) 31 {32 if (ModelState.IsValid) 33 {34 var webapiUrl = "http://localhost:1001/s/add";" 35 var httpResponseMsg = new HttpResponseMessage (); 36 37 using (var httpClient = new HttpClient ()) 38 {39 httpResponseMsg = await httpClient.PostAsync (webapiUrl, model, new System.Net.Http.Formatting.JsonMediaTypeFormatter ()); 40} 41 model = httpResponseMsg.Content.ReadAsAsync () .Result 42} 43 44 ModelState.AddModelError ("", model.Id > 0? "add success": "add failed"); 45 return View (model); 46} 47}

There are a few points to note here. The HttpClient class is mainly used for API requests. Here, I request the webapi address http://localhost:1001/s/all01_2 we just created by passing parameters to her extended PostAsync method. Let's take a brief look at the parameters used in this method:

View Code

It is worth noting that the last parameter new System.Net.Http.Formatting.JsonMediaTypeFormatter (), the JsonMediaTypeFormatter class inherits the MediaTypeFormatter class and overrides some formatting methods. Because the api project we created requires parameters and returns in json format, we use the JsonMediaTypeFormatter class here, as well as other formats such as XmlMediaTypeFormatter, which were also used in the last sharing article. The PostAsync method is asynchronous, so we need to use await modification when calling. With await, we naturally need to have her matching combination async and Task, so we have our public async Task Index () code. OK, there is too much nonsense. Let's take a look at the query results after trying to bind the code in view and bind the student list:

View Code

After executing the Index method of the student list Action, the effect in the browser is as follows:

After seeing the result, our example of mvc calling webapi is successful. Let's take a look at the add function. The main code for calling webapi in the add method is almost the same as the code for querying the student list method, except that the result returned after calling the api method is that the information of a single student object is not a collection. Just paste the Add view code here for your reference:

View Code

It is worth noting that this background requests api interfaces between different domains, and there are no cross-domain restrictions. Unless there are restrictions on the interface itself, the ajax method to be explained below will be different.

How to adjust the api interface by ajax

First of all, we need to make it clear that the ajax call interface cannot be cross-domain, which must be understood. For example, the webapp of the mobile phone H6 usually uses ajax to call the interface to obtain data, and most of the requirements are requested across domains, so this example will briefly mention several commonly used processing methods in the following explanation, and use one of them to explain, hoping to give you some help. To test cross-domain access, we added the following layout code to the attempt of the previous node:

View Code

Then, the jquery binds the query button event code such as:

1 2 3 $(function () {4 5 $("# btnSearch"). On ("click", function () {6 7 var tabObj = $("# tab tbody"); 8 tabObj.html ('tr > loading.') 9 10 $.post ("http://localhost:1001/s/all01_2", {}, function (data) {11 12 var tabHtml = []; 13 $.each (data, function (I, item) {14 15 tabHtml.push ('); 16 tabHtml.push ("+ item.Id +") 17 tabHtml.push ("+ item.Name +"); 18 tabHtml.push ("" + (item.Sex? "male": "female") + "); 19 tabHtml.push (" + item.Birthday + "); 20 tabHtml.push ('); 21}); 22 if (tabHtml.length 0? "add success": "add failed"); 20} else {21 divResult.html ("); 22} 23}); 24}); 25}) 26 27

The corresponding API for adding student information:

1 [Route ("add")] 2 [HttpPost] 3 public HttpResponseMessage AddStudent (MoStudent moStudent) 4 {5 var httpStatus = HttpStatusCode.OK; 6 if (ModelState.IsValid) 7 {8 var isfalse = db.Save (moStudent); 9} 10 return Request.CreateResponse (httpStatus, moStudent); 11}

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report