在上一篇博文中说了一下 web API 在 MVC4 中使用的样例。但有些时候我们只是想使用 Web API 的功能,而不需要使用整个的 MVC,这个时候就该抛开 MVC4 来新建项目了。
首先要新建一个 asp.net 空应用程序,在程序中添加引用 System.Web.Http 和 System.Web.Http.WebHost:
继续添加 System.Net.Http
另外还需要引用 Json.net,可以通过 Nuget 或者直接用用下载好的 dll
添加路由映射
这一步和上一篇中讲的一样,我们可以直接把上一篇的配置拿过来:
- public class WebApiConfig
- {
- public static void Register(HttpConfiguration config)
- {
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
- }
- }
新建 Global.asax 文件,在 Application_Start 中调用完成注册
- protected void Application_Start(object sender, EventArgs e)
- {
- WebApiConfig.Register(GlobalConfiguration.Configuration);
- }
创建 Web API Controller
先在项目中把 UserModel 添加到项目中
- public class UserModel {
- public string UserID {
- get;
- set;
- }
- public string UserName {
- get;
- set;
- }
- }
在项目中新建 API 目录,把上一篇中的 UserController 直接拿过来
- public class UserController : ApiController
- {
- public UserModel getAdmin()
- {
- return new UserModel() { UserID = "000", UserName = "Admin" };
- }
- public bool add(UserModel user)
- {
- return user != null;
- }
- }
运行上一篇的测试程序吧
参考页面:m/p/5933752.html
来源: http://www.bubuko.com/infodetail-1955706.html