asp.net mvc项目创建WebApi简单例子
1、创建默认路由的映射。
namespace RedisDemo.App_Start { public class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional }); } } }
2、在Global.asax的 Application_Start 方法中注册路由。(注册要在默认路由之前,WebApiConfig在RouteConfig之前)
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); WebApiConfig.Register(GlobalConfiguration.Configuration); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } }
3、新建ApiController,并访问http://localhost:47337/api/demo/getlist
public class DemoController : ApiController { public List<User> GetList() { var list = new List<User> { new Models.User { Id=1, Age="20", Name="张三", Sex=1, UID=1 }, new Models.User { Id=2, Age="21", Name="张四", Sex=1, UID=2 }, new Models.User { Id=3, Age="22", Name="张五", Sex=1, UID=3 }, new Models.User { Id=4, Age="23", Name="张六", Sex=1, UID=4 } }; return list; } }
WebApi接口参数详解见:http://www.cnblogs.com/landeanfen/archive/2016/04/06/5337072.html
请随手写下你的想法!!!