先简单介绍下:
webAPI在这边特指ASP.NET Web API。
在不想使用大型结构繁琐的规则和约束的webserver还有WCF框架时,WebAPI是非常好的选择,用一张图来说明webAPI的优势。

微软现在的MVC框架里已自带有WebAPI模板,熟悉MVC的同学直接创建就行。
1.首先放一下结构,可以清楚的了解。

还是比较清晰的看出MVC的影子。
我这边是写了webapi,在index文件中用js来调用。
2.配置WebAPIConfig路由选择器。
namespace WebAPI
{
public class WebAPIConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
3.配置Global.asax文件
protected void Application_Start(object sender, EventArgs e)
{
//在应用程序启动时注册路由映射
WebAPIConfig.Register(GlobalConfiguration.Configuration);
}
4.先在Model中建一个User的原型,再在Controller中创建User的控制器,命名为UserController。
User:
namespace WebAPI.Model
{
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string NickName { get; set; }
public int Age { get; set; }
}
}
UserController:
namespace WebAPI.Controller
{
public class UserController : ApiController
{
public HttpResponseMessage GetUser()
{
List<User> users = new List<User>();
User user = new User();
user.Age = 10;
user.Id = 1;
user.Name = "java";
user.NickName = "nick";
users.Add(user);
User user2 = new User();
user2.Age = 12;
user2.Id = 2;
user2.Name = "C";
user2.NickName = "n";
users.Add(user2);
string value = JsonHelper.JsonAddHeader(users,"0","success");
HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(value, Encoding.GetEncoding("UTF-8"), "application/json") };
return result;
}
}
}
html页面使用js调用:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="Scripts/jquery-1.8.2.min.js"></script>
<script>
$(function () {
$("#select").click(function () {
$.get("api/user/getuser", function (data) {
document.write(data);
});
});
})
</script>
</head>
<body>
<input id="select" type="button" value="提交" />
</body>
</html>
文章评论