The Web API is part of the ASP. NET core platform, which leverages the underlying capabilities of the MVC framework to facilitate our rapid development of deployment Web services. We can create a Web API service in a regular MVC application by adding API controllers, and the normal MVC application controller returns ACTIONRESULT based on the action method requested by the user, while the Web API service returns the JSON encapsulated model data.
The code for the relevant class and interface is given before starting the following content:
Public interface Ireservationrepository {ienumerable<reservation> GetAll (); Reservation Get (int id); Reservation Add (reservation item); void Remove (int id); BOOL Update (reservation item); }public class Reservation {public int Reservationid {get; set;} public string ClientName {get; set;} public string location {get; set;} }public class Reservationrepository:ireservationrepository {private list<reservation> data = new List<r eservation> {New Reservation {Reservationid = 1, ClientName = "Adam", location = "London"}, New reservation {Reservationid = 2, ClientName = "Steve", location = "New York"}, new Reservation {Reservationid = 3, ClientName = "Jacqui", location = "Paris"},}; private static reservationrepository repo = new Reservationrepository (); public static Ireservationrepository Getrepository () {return repo; } public ienumerable<reservation> GetAll () {return data; Public reservation Get (int id) {var matches = data. Where (r = = R.reservationid = = ID); return matches. Count () > 0? Matches. First (): null; } Public reservation ADD (reservation item) {Item. Reservationid = data. Count + 1; Data. ADD (item); return item; } public void Remove (int id) {Reservation item = Get (ID); if (item! = NULL) {data. Remove (item); }} public bool Update (reservation item) {Reservation Storeditem = Get (item). Reservationid); if (Storeditem! = null) {Storeditem.clientname = Item. ClientName; Storeditem.location = Item. Location; return true; } else {return false; } } }
Creating an API Controller
To add an API controller to an existing MVC Web app to create a Web service, the Add Controller dialog for VS has the option of creating an API controller, and we can choose "Empty API Controller" to create a null API director that does not contain any methods. Manually add a method that corresponds to each Web service operation, similar to a complete API control class:
Using system.collections.generic;using system.web.http;using webservices.models;namespace WebServices.Controllers { Public class Reservationcontroller:apicontroller { ireservationrepository repo = Reservationrepository.getrepository (); Public ienumerable<reservation> getallreservations () { return repo. GetAll (); } Public reservation getreservation (int id) { return repo. Get (ID); } Public reservation postreservation (reservation item) { return repo. ADD (item); } public bool Putreservation (reservation item) { return repo. Update (item); } public void deletereservation (int id) { repo. Remove (ID);}}}
When we access/api/reservation from the browser, we get the JSON data encapsulated by the Getallreservations method, which results in a similar result in IE10:
In the case of Chrome or Firefox, the result is XML:
This difference originates from the accept header submitted by the browser, similar to the Accept header sent by IE10:
... Accept:text/html, Application/xhtml+xml, */* ...
Indicates that IE10 first accepts text/html, followed by Application/xhtml+xml, and if the first two are not, */* means accept any format. The WEB API supports XML and JSON two formats, but takes precedence with JSON, so IE10 gets the JSON format of the */* selection. Chrome sends an accept header like this:
Chrome first accepts Application/xml, so the Web API sends data in XML format.
Understand how API controllers work
In IE10, if you access/API/RESERVATION/3, the resulting JSON data is similar:
{"Reservationid": 3, "ClientName": "Jacqui", "Location": "Paris"}
This gets the Reservationidvalue=3 object data, which is similar to the MVC path mapping, and indeed, the API has its own path mapping, defined in the WebApiConfig.cs file:
Using System.web.http;namespace webservices {public static class Webapiconfig {public static void Register ( Httpconfiguration config) { config. Routes.maphttproute ( name: "Defaultapi", routetemplate: "Api/{controller}/{id}", defaults:new {id = Routeparameter.optional} );}}}
The path mapping here is very similar to the path mapping of the MVC controller, But the path mapping tables and configuration classes used are all from the System.Web.Http namespace, and Microsoft has replicated the corresponding classes of MVC in this namespace, which allows us to use the Web API separately from MVC. The API path mappings registered here are finally registered with the global configuration file via Webapiconfig.register (globalconfiguration.configuration) in Global.asax.
Unlike the MVC controller, which chooses the action method via a URL, the API controller chooses the API controller method based on the HTTP request method. The naming convention for API controller methods is generally the HTTP method prefixed with the name of the controller, such as Getreservation (which is just the general practice, dogetreservation, thisisthegetaction are allowed), which we access from the browser The HTTP method used by/api/reservation is for the GET,API controller to find all the controller methods that contain get, getreservation and getallreservations are considered, However, the specific choice of which also refer to the parameters, Access/api/reservation without any parameters, so the API controller selected Getallreservations, Access/api/reservation/ 3 naturally chose the getreservation. Thus we also know that postreservation, putreservation, deletereservation respectively corresponding to the HTTP post, Put, delete three methods (WEB API representation state Transfer-rest).
Putreservation method name is somewhat unnatural, we are more accustomed to call it updatereservation, and like MVC, System.Web.Http also provides some features that can be applied to controller methods:
public class Reservationcontroller:apicontroller { ireservationrepository repo = Reservationrepository.getrepository (); Public ienumerable<reservation> getallreservations () { return repo. GetAll (); } Public reservation getreservation (int id) { return repo. Get (ID); } [HttpPost] Public reservation createreservation (reservation item) { return repo. ADD (item); } [Httpput] public bool Updatereservation (reservation item) { return repo. Update (item); } public void deletereservation (int id) { repo. Remove (ID); } }
Here, the HttpPost feature is specified to createreservation the POST request for HTTP, httpput specifies the put request of the updatereservation corresponding to HTTP, and MVC has a similar feature. But note that although they have the same name, they are defined in the System.Web.Http namespace.
Using the Web API
Like regular Web services, there are several ways to invoke Web APIs, such as Windows Form programs, other ASP. NET applications, and here's how to use the Web API with JavaScript scripts in your current MVC application.
View File index.cshtml:
@{viewbag.title = "Index";} @section Scripts {<script src= "~/scripts/jquery.unobtrusive-ajax.js" ></script> <script src= "~/script S/home/index.js "></script>}<div id=" Summarydisplay "class=" display "> Index.js:
function Selectview (view) {$ ('. Display '). Not (' # ' + view + "display"). Hide (); $ (' # ' + view + "Display"). Show (); function GetData () {$.ajax ({type: "GET", url: "/api/reservation", success:function (data) { $ (' #tableBody '). empty (); for (var i = 0; i < data.length; i++) {$ (' #tableBody '). Append (' <tr><td><input id= "id" NA Me= "id" type= "Radio" ' + ' value= "' + data[i]. Reservationid + '/></td> ' + ' <td> ' + data[i]. ClientName + ' </td> ' + ' <td> ' + data[i]. Location + ' </td></tr> '); } $ (' Input:radio ') [0].checked = "checked"; Selectview ("Summary"); } });} $ (document). Ready (function () {Selectview ("summary"); GetData (); $ ("button"). Click (function (e) {var Selectedradio = $ (' input:radio:checked ') switch (e.target.id) { Case "Refresh": GetData (); Break Case "Delete": $.ajax ({type: "delete", url: "/api/reservation/" + SE Lectedradio.attr (' value '), Success:function (data) {selectedradio.closest (' tr ') ). Remove (); } }); Break Case "Add": Selectview ("add"); Break Case "edit": $.ajax ({type: "GET", url: "/api/reservation/" + selecte Dradio.attr (' value '), Success:function (data) {$ (' #editReservationId '). val (dat A.reservationid); $ (' #editClientName '). Val (data. ClientName); $ (' #editLocation '). Val (data. Location); Selectview ("edit"); } }); Break Case "SubmitEdit": $.Ajax ({type: "PUT", url: "/api/reservation/" + selectedradio.attr (' value '), Data: $ (' #editForm '). Serialize (), success:function (Result) {if (re Sult) {var cells = selectedradio.closest (' tr '). Children (); Cells[1].innertext = $ (' #editClientName '). Val (); Cells[2].innertext = $ (' #editLocation '). Val (); Selectview ("Summary"); } } }); Break } });});
The first access to the index view after loading the HTML interface is called the JS function Selectview ("Summary"), which shows the Id=summarydisplay div block, hiding the other adddisplay, editdisplay blocks, Then by calling the JS function GetData (), GetData uses the Get method to request data to the Web API, and the returned data is one row per item in the table. At the bottom of the summarydisplay are the refresh, ADD, Edit, delete four buttons, which click on "$ (" button "). Click (Function (e)" processing; call GetData refresh data when clicking Refresh Click Add to hide other div blocks, display adddisplay div block, this div block creates an Ajax form, post method submits to API controller Createreservation;edit button according to current options from/api/ Reservation/{id} get the corresponding object to display the Editdisplay div block while hiding other div blocks, click the SubmitEdit button in the Editdisplay div block, JS use the Put method to request/api/ RESERVATION/{ID} calls the API controller's Updatereservation method to modify the data, and then displays the Summarydisplay div block again, hiding the other div blocks, and clicking the Delete button is using the Delete method request/ API/RESERVATION/{ID} calls the Controller method deletereservation Delete the object, and then deletes the corresponding row in the Summarydisplay div block.
The above is a summary of the contents of the fourth edition of the Apress Pro ASP. NET MVC 4, as described in the original http://www.apress.com/9781430242369.
ASP. NET MVC 4 (12) Web API