经过我三篇文章的解惑,webapi我相信大家没有问题了!
先创建了一个UserModel
public class UserModel{public string UserID { get; set; }public string UserName { get; set; }
}
登录后复制
然后添加Web API Controller
public class UserController : ApiController{public UserModel getAdmin()
{return new UserModel() { UserID = "000", UserName = "Admin" };
}
}
登录后复制
注册路由
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
登录后复制
在Global中注册
protected void Application_Start(object sender, EventArgs e)
{WebApiConfig.Register(GlobalConfiguration.Configuration);
}
登录后复制
这个时候用地址栏访问地址:api/user/getadmin
这个时侯默认返回的是XML数据模型。
使用AJAX请求这个api,指定数据格式为json
$.ajax({
type: 'GET',
url: 'api/user/getadmin',
dataType: 'json',
success: function (data, textStatus) {
alert(data.UserID + " | " + data.UserName);
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
}
});
登录后复制
alert出来的结果是:
这样看来,真的是dudu所说的,可以根据请求的数据类型返回指定的数据格式。
POST数据
修改一下controller,添加一个add方法
public bool add(UserModel user)
{return user != null;
}
登录后复制
只为了测试,所以这里只判断一下传入的实体是否为空,如果不为空则返回true
我在页面上添加了一个button,代码如下:
<input type="button" name="btnOK" id="btnOK" value="发送POST请求" />
登录后复制
添加JS代码
$('#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) {
}
});
});
登录后复制
再次运行页面
我们附加进程进行调试,在发送ajax请求的时候,服务器段接收到的数据如图:
如果认为此文对您有帮助,别忘了支持一下哦!
以上就是怎么操作 ASP.NET Web API ?的详细内容,更多请关注靠谱客其它相关文章!
最后
以上就是洁净芹菜最近收集整理的关于怎么操作 ASP.NET Web API ?的全部内容,更多相关怎么操作内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复