一、添加WebApi项目
二、nuget下载WebApi所需的类库引用
install-package Microsoft.AspNet.WebApi
install-package Microsoft.Owin.Host.SystemWeb
install-package Microsoft.AspNet.WebApi.Cors
三、WebApi基础配置
配置webapi路由、跨域支持
public static class WebApiConfig { public static void Register(HttpConfiguration config) { //跨域配置 config.EnableCors(new EnableCorsAttribute("*", "*", "*")); //webApi路由 config.MapHttpAttributeRoutes(); //设置webapi路由规则 config.Routes.MapHttpRoute( name: "AreaApi", routeTemplate: "api/{area}/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Routes.MapHttpRoute( name: "WebApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); //移除xml返回格式数据 GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); //配置返回的时间类型数据格式 GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Add( new Newtonsoft.Json.Converters.IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" } ); } }
注册webapi
public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); } }