1.在App_Start文件夹新建WebApiConfig.cs文件,建立webApi路由的注册方法。
using System.Web.Http;namespace PrivilegeManager
{public class WebApiConfig{public static void Register(HttpConfiguration config){config.MapHttpAttributeRoutes();config.Routes.MapHttpRoute(name: "DefaultApi",routeTemplate: "api/{controller}/{action}/{id}",defaults: new { id = RouteParameter.Optional });}}
}
2.修改Global.asax启动项,注册webApi路由(注意要在MVC路由之前注册)。
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;namespace PrivilegeManager
{public class MvcApplication : System.Web.HttpApplication{protected void Application_Start(){AreaRegistration.RegisterAllAreas();GlobalConfiguration.Configure(WebApiConfig.Register);//api路由注册要在mvc前面FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);RouteConfig.RegisterRoutes(RouteTable.Routes);//mvc路由注册BundleConfig.RegisterBundles(BundleTable.Bundles);}}
}
3.建立API Controller
using System;
using System.Collections.Generic;
using System.Web.Http;namespace PrivilegeManager.Controllers
{public class DataApiController : ApiController{[HttpPost]//此方法实际访问地址:ip地址/api/DataApi/GetTestpublic Object GetTest(QueryCommon query){//入参是json格式,会自动转成实体。返参的实体也会自动转成json格式list = List<实体>();return list;}}
}