Original: ASP. NET Core series "five" Webapi finishing and restful styling
Introduced
What is restful? Here do not repeat, details please Baidu!
Haha, would also like to Balabala introduce some webapi, restful, or forget, we directly on dry! (The reason is lazy!) haha
Use
People who have used MVC before should be familiar with WEBAPI, first look at a familiar code
What did you guys find out? Much the same as the previous MVC, but in some places different, let's see what the difference is.
1. First Sysuserscontroller a piece of code above
[Produces ("application/json")] // [Route ("Api/sysusers")] [Route ("api/[controller]/[action]")] Public class Sysuserscontroller:controller { }
The part of the comment first regardless, first we receive the JSON format content, then the route is api/[controller]/[action]
In this case, we only need normal AJAX requests to access it.
$.ajax ({URL:'/api/sysusers/login ', type:' POST ', ContentType:"Application/json; Charset=utf-8 ", data: {UserName:' Shumin ', Password: ' 123456 '}, Success:function(data) {if(data.success) {varhref = ' @Url. Action ("Index")? ' +NewDate (). GetTime (); Window.location.href=href; } Else{alert (data.message); }}, Error:function() {alert (' Service-side error '); } });
We run it, we find we can't get the data,
This is for what, after many attempts, is the foreground HTTP request is not correct, because we agreed to the JSON transfer, so the data needs to be serialized
$.ajax ({URL:'/api/sysusers/login ', type:' POST ', ContentType:"Application/json; Charset=utf-8 ", Data:JSON.stringify ({UserName:' Shumin ', Password: ' 123456 '}), Success:function(data) {if(data.success) {varhref = ' @Url. Action ("Index")? ' +NewDate (). GetTime (); Window.location.href=href; } Else{alert (data.message); }}, Error:function() {alert (' Service-side error '); } });
There is one more thing to be aware of, the AJAX default
ContentType is application/x-www-form-urlencoded.
We need to change into Application/json; Charset=utf-8
So we can get the data.
RESTful
Recommend an introductory article about restful HTTP://WWW.RUANYIFENG.COM/BLOG/2014/05/RESTFUL_API
Using the method above will cause the URL to stink and grow, for example
Website:/get_user?id=3
RESTFUL:GET/USER/3 (GET is HTTP type)
We used to write HTTP requests and only get post two,
The corresponding resources for registration are USER,API as follows:
GET/USER/:ID # Get ID user's information
Post/user # Create a new User (register)
PUT/USER/:ID # Update ID user's information
DELETE/USER/:ID # Delete ID User (logoff)
Let's take a look at the features of the RESTful API:
- Based on "Resources", data and services, everything is a resource in restful design.
- No status. A call typically returns a result, and there is no such dependency on the last call as "open connection-access data-close connection".
- Verbs are usually not present in URLs, only nouns
- URL semantics clear and unambiguous
- Use the GET, POST, DELETE, put of HTTP to indicate additions and deletions to a resource
Using JSON without XML
Let's take a look at some of the best practice principles of the RESTful API:
- Use HTTP verbs to indicate additions and deletions, GET: Query, POST: Add, PUT: Update, delete: delete
- The return result must use JSON
- The HTTP status code, which has a specific meaning in rest: 200,201,202,204,400,401,403,500. For example, 401 means the user authentication failed, 403 means that you verify the identity passed, but this resource you can not operate.
The RESTful API is directly attached here for reference only
namespacenetcoreadmin.controllers{[Produces ("Application/json")] [Route ("api/sysusers")] Public classSysuserscontroller:controller {Private ReadOnlyEfcorecontext _context; PublicSysuserscontroller (Efcorecontext context) {_context=context; } //get:api/sysusers[HttpGet] PublicIenumerable<sysuser>getsysusers () {return_context. SysUsers; } //GET:API/SYSUSERS/5[HttpGet ("{ID}")] Public AsyncTask<iactionresult> Getsysuser ([Fromroute]intID) {if(!modelstate.isvalid) {returnbadrequest (modelstate); } varSysuser =await_context. Sysusers.singleordefaultasync (m = m.id = =ID); if(Sysuser = =NULL) { returnNotFound (); } returnOk (Sysuser); } //PUT:API/SYSUSERS/5[Httpput ("{ID}")] Public AsyncTask<iactionresult> Putsysuser ([Fromroute]intID, [frombody] Sysuser Sysuser) { if(!modelstate.isvalid) {returnbadrequest (modelstate); } if(id! =sysuser.id) {returnbadrequest (); } _context. Entry (Sysuser). State=entitystate.modified; Try { await_context. Savechangesasync (); } Catch(dbupdateconcurrencyexception) {if(!sysuserexists (ID)) { returnNotFound (); } Else { Throw; } } returnnocontent (); } //post:api/sysusers[HttpPost] Public AsyncTask<iactionresult>Postsysuser ([frombody] Sysuser sysuser) {if(!modelstate.isvalid) {returnbadrequest (modelstate); } _context. Sysusers.add (Sysuser); await_context. Savechangesasync (); returnCreatedataction ("Getsysuser",New{id =sysuser.id}, Sysuser); } //DELETE:API/SYSUSERS/5[Httpdelete ("{ID}")] Public AsyncTask<iactionresult> Deletesysuser ([Fromroute]intID) {if(!modelstate.isvalid) {returnbadrequest (modelstate); } varSysuser =await_context. Sysusers.singleordefaultasync (m = m.id = =ID); if(Sysuser = =NULL) { returnNotFound (); } _context. Sysusers.remove (Sysuser); await_context. Savechangesasync (); returnOk (Sysuser); } Private BOOLSysuserexists (intID) {return_context. Sysusers.any (E = E.id = =ID); } }}
NET Core series "five" Webapi finishing and restful styling