Home >Backend Development >C#.Net Tutorial >How to operate ASP.NET Web API?
After clearing up the confusion in my three articles, I believe everyone has no problem with webapi!
First create a UserModel
public class UserModel{public string UserID { get; set; }public string UserName { get; set; } }
Then add Web API Controller
public class UserController : ApiController{public UserModel getAdmin() {return new UserModel() { UserID = "000", UserName = "Admin" }; } }
Register Route
public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); }
Register in Global
protected void Application_Start(object sender, EventArgs e) {WebApiConfig.Register(GlobalConfiguration.Configuration); }
At this time, use the address bar to access the address: api/user/getadmin
At this time, the XML data model is returned by default .
Use AJAX to request this api, specify the data format as json
$.ajax({ type: 'GET', url: 'api/user/getadmin', dataType: 'json', success: function (data, textStatus) { alert(data.UserID + " | " + data.UserName); }, error: function (xmlHttpRequest, textStatus, errorThrown) { } });
The result of alert is:
It seems like this, really What dudu said is that the specified data format can be returned according to the requested data type.
Modify the controller and add an add method
public bool add(UserModel user) {return user != null; }
Just for testing, so here we only judge whether the incoming entity is Empty, if not empty it returns true
I added a button on the page, the code is as follows:
<input type="button" name="btnOK" id="btnOK" value="发送POST请求" />
Add JS code
$('#btnOK').bind('click', function () {//创建ajax请求,将数据发送到后台处理var postData = { UserID: '001', UserName: 'QeeFee'}; $.ajax({ type: 'POST', url: 'api/user/add', data: postData, dataType: 'json', success: function (data, textStatus) { alert(data); }, error: function (xmlHttpRequest, textStatus, errorThrown) { } }); });
Run the page again
We attach the process for debugging. When sending an ajax request, the data received by the server segment is as shown in the figure:
If you think this article is helpful to you, don’t forget to support it!
The above is the detailed content of How to operate ASP.NET Web API?. For more information, please follow other related articles on the PHP Chinese website!