First, the serialization in Core Webapi
Using Newtonsoft.json, custom global configuration processing:
// This method gets called by the runtime. Use this method to add services to the container. public void configureservices (iservicecollection services) { // use Imvcbuilder to configure JSON serialization processing services. Addmvc (). Addjsonoptions (Options => {options. Serializersettings.contractresolver = new Defaultcontractresolver (); Options. serializersettings.dateformatstring = YYYY-MM-DD ; });}
Second, the route processing in Core Webapi is handled using method annotations,
Controller routing: [Route ("Api/menu")]
Action route: 1. According to HttpMethod Route [Httpput] 2. Route [HttpGet ("{ID}") according to template templates]
Returns data processing in Core WEBAPI, providing more options:
1.okresult,okobjectresult, the return status is 200
Note: The Okobjectresult front desk jquery automatically resolves to object objects and does not need to be deserialized
2.ContentResult return string
3.JsonResult return JSON object, foreground does not need deserialization processing
4. Return the underlying type and reference type, auto-serialize, foreground receive As object objects, etc.
Iii. based on HttpMethod routing example
1.API definition
/* * The API is defined as follows * get api/menu get menu list * POST api/menu Add Module * PUT Api/menu Modify Module * PATCH api/menu Modify menu Information * Delete api/menu Delete module * /
2. Background code:
Menumodelcontext _context =NewMenumodelcontext ();/// <summary>///Get list/// </summary>/// <returns></returns>[HttpGet] PublicIenumerable<menu>Get () {List<Menu> list =_context.menu.tolist (); returnlist;}/// <summary>///Add a Module object/// </summary>/// <param name= "M" ></param>/// <returns></returns>[HttpPost] Public BOOLAdd (Model m) {Try{m.addtime=DateTime.Now; _context.model.add (m); _context.savechanges (); return true; } Catch(Exception ex) {return false; }}/// <summary>///modifying Modules/// </summary>/// <param name= "M" ></param>/// <returns></returns>[Httpput] Public BOOLUpdate (Model m) {Try{Model Oldmodel=_context.model.find (m.modelid); Oldmodel.modelname=M.modelname; Oldmodel.sortnumber=M.sortnumber; _context.savechanges (); return true; } Catch(Exception ex) {return false; }}/// <summary>///Modifying a Menu object/// </summary>/// <param name= "M" ></param>/// <returns></returns>[Httppatch] Publiciactionresult Update (Menu m) {Try{Menu Oldmenu=_context.menu.find (M.MENUID); if(Oldmenu = =NULL) returnNotFound ("the menu you want to access does not exist or has been deleted"); Oldmenu.menuname=M.menuname; Oldmenu.sortnumber=M.sortnumber; Oldmenu.modelid=M.modelid; _context.savechanges (); returnOk (); } Catch(Exception ex) {returnContent (ex. Message); }}/// <summary>///Deleting a module/// </summary>/// <param name= "IDs" ></param>/// <returns></returns>[Httpdelete] PublicIactionresult Delete (stringIDs) { Try { if(string. IsNullOrEmpty (IDS))Throw NewException ("failed to get ID parameter"); List<int> idlist = IDs. Split (','). Select (q =Convert.ToInt32 (q)). ToList (); List<Model> list = _context.model.where (q =idlist.contains (Q.modelid)). ToList (); _context.model.removerange (list); intCount =_context.savechanges (); //use Okobjectresult foreground jquery to automatically resolve to object objects without deserialization//returned not a string returnOk (New{msg= $"Delete succeeded, total delete {count} bar data" }); } Catch(Exception ex) {//using Contentresult to return string processing returnContent (ex. Message); }}
View Code
3.jQuery Ajax Code
//Get get list datafunctionTestone () {$.get (Urlhelper.getapi (' Menu '), {},function(data) {console.info (data); varMenu1 =NewVue ({el:' #menu1 ', data: {result:data}}); })}testone ();//Add MenuvarExample2 =NewVue ({el:' #example-2 ', data: {name:' Add menu ' }, //defining methods in a Methods objectmethods: {addMenu:function(event) {//add a menu using post submission var_this = This; This. Name = ' Committing ... '; $.post (Urlhelper.getapi (' Menu '), {modelname:' Test Menu 5 ', Sortnumber:5 }, function(data) {console.info (data); _this.name= ' Submit Success '; }); }, Updatemodel:function(event) {//modifying a module with put commit var_this = This; $.ajax ({url:urlHelper.getApi (' Menu '), type:' Put ', data: {modelid:' 4 ', ModelName:' Module ABC ', Sortnumber:4}, Success:function(data) {console.info (data); if(Data = =true) Alert (' Modified Success '); ElseAlert (' Modify failed '); } }); } }});//Modify menu, delete modulevarBtngroup1 =NewVue ({el:' #btngroup1 ', data: {name:' Modify Menu ', name1:' Delete module '}, methods: {updatemenu:function(e) {var_this = This; //Modify a menu using patch mode$.ajax ({url:urlHelper.getApi (' Menu '), type:' Patch ', data: {MenuID:1, MenuName:' Test Menu One ', Sortnumber:100, ModelID:2}, Success:function(data) {console.info (data); } }); }, DeleteMenu:function(e) {//Delete a module using delete submission$.ajax ({url:urlHelper.getApi (' Menu '), type:' Delete ', data: {ids:[1003]}, Success:function(data) {console.info (data); }, Error:function(data) {console.info (data); } }); } }});
View Code
Iv. Template Routing example based on HttpMethod
1.API definition
/* * API definition * Get Api/menu/{id} Gets the specified ID of the menu object * get api/menu/getmodel Get module List contents * /
2. Background code:
[HttpGet ("{ID}")]public iactionresult Get (int ID) { = _context.menu.find (ID); if NULL ) return NotFound (); return Json (m);} // Special Note: The value of the template in a route may not contain a slash/ [HttpGet ("Getmodel")] public Iactionresult Getmodel () { list<Model> list = _ Context.Model.ToList (); return Json (list);}
3.Jquery of Ajax Code
//Other Get mode testsvarBtngroup2 =NewVue ({el:' #btngroup2 ', data: {name:' Get Menu object ', name1:' Get module list ', item: {}//Vue Object Binding, no case requires an empty object, otherwise error}, methods: {getmenu:function(e) {var_this = This; //link address format: http://localhost:50000/api/menu/1/$.get (Urlhelper.getapi (' Menu ', ' 1 '), {},function(data) {console.info (data); _this.item=data; }); }, Getmodel:function(e) {var_this = This; $.get (Urlhelper.getapi (' Menu ', ' Getmodel '), {},function(data) {console.info (data); }) } }});
For more information:
ASP. NET Core Webapi Getting Started (i)
JSON serialization processing in ASP.
. The use and arrangement of Efcore in Netcore (II.)-association Table query
ASP. NET Core Webapi get started (b) Simple example