上篇:webapi快速框架搭建-建立項目(一)html
空項目默認是沒有webapi相關的dll,要本身去nuget裏安裝。web
using System; using System.Web.Http; namespace webapi { public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { #region webapi的相關配置 // GlobalConfiguration在Microsoft.AspNet.WebApi.Core裏,用nuget添加Microsoft.AspNet.WebApi GlobalConfiguration.Configure(config => { // Web API 路由 config.MapHttpAttributeRoutes();//啓用webapi的屬性路由 // 配置webapi的默認路由模板 config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); }); #endregion } protected void Session_Start(object sender, EventArgs e) { } protected void Application_BeginRequest(object sender, EventArgs e) { } protected void Application_AuthenticateRequest(object sender, EventArgs e) { } protected void Application_Error(object sender, EventArgs e) { } protected void Session_End(object sender, EventArgs e) { } protected void Application_End(object sender, EventArgs e) { } } }
打開win10的iis管理器,建立一個網站,以下圖。express
固然也能夠用vs自帶的iis express,直接運行(按f5)就能夠了。在開發時可用iis express快速的調試,但部署時就得用上iis了。api
我在開發時習慣部署到iis上,這樣開發時只要編譯程序後就直接能夠用postman來訪問webapi接口是否正常,不用每次都啓動iis express,這樣速度有點慢,更方便的是能夠用vs的調試--》附加到進程,來對已經發布的webapi接口網站進行調試,甚至只以遠程調試服務器上的iis網站來排查問題。服務器
建立webapi接口控制類mvc
using System.Web.Http; namespace webapi.example { public class TestController : ApiController { public IHttpActionResult Get() { return Ok("this is TestController.Get()"); } } }
編譯後用postman訪問接口的地址:http://localhost:101/api/testapp
webapi的路由和控制器在網站有不少教程,可自行學習,我我的建議看webapi的官網教程就好了,有中文版的,已經說的很清楚了,也更權威框架
webapi官方文檔:webapi路由post