给现有MVC 项目添加 WebAPI
1. 增加一个WebApi Controller, VS 会自动添加相关的引用,主要有System.Web.Http,System.Web.Http.WebHost,System.Net.Http
2. 在App_Start 下创建 WebApiConfig.cs 并注册路由
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Http; namespace Libaray.Web.App_Start { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API 配置和服务 // Web API 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
3. 在Global.asax, Application_Start 下添加 WebAPI 配置
using Libaray.Web.App_Start; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace Libaray.Web { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
4. 在第一步添加的WebApi 中填写相应代码,
using Libaray.Web.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace Libaray.Web.Controllers { [RoutePrefix("api/SystemUsers")] public class SystemUsersController : ApiController { [HttpGet, Route("GetUserList")] public List<UserModel> GetUserModels() { UserModelService UserBS = new UserModelService(); return UserBS.FindList(u => u.isActive == true); } [HttpGet, Route("GetUser")] public UserModel GetUserModel(int id = 0) { if(id != 0) { UserModelService UserBS = new UserModelService(); return UserBS.Find(u => u.Id == id); } else { return null; } } [HttpPost, Route("Login")] public bool Login(string loginId,string password) { UserModelService UserBS = new UserModelService(); return UserBS.ValidateLoginInfo(loginId, password); } } }
5. Run the application and call the API. Example: http://localhost:49919/api/SystemUsers/GetUserList
-----------------------------------------------------------------