vs 2013 有自带的web API 项目,(如图1-1)而vs 2012 的需要新建一个mvc 应用程序,然后使用nugut, 控制台模式 输入安装命令:
Install-Package Microsoft.AspNet.WebApi,会自动把webapi 需要的dll包安装到你的项目。
图:1-1
当你运行混合有mvc 和web api 的项目时,asp.net 会使用 HttpApplication.MapRequestHandler(在选择了用来响应请求的处理程序),来决定哪一种http 处理程序去处理请求,当路由匹配的时候,会产生一个IRouteHandler ,IRouteHandler的目的是创建一个IHttpHandler 去处理请求, 如果的 IRouteHandler 是一个 HttpControllerRouteHandler , 那么就会走webapi 路线,如果是MvcRouteHandler 那么就走mvc
在底层,web api 是建立在 IHttpAsyncHandler 的异步处理程序上的,它的作用是拦截和处理向服务器发出的请求和响应客户端。
public interface IHttpAsyncHandler : object, IHttpHandler
{
System.IAsyncResult BeginProcessRequest(HttpContext context, System.AsyncCallback cb,
object extraData);
void EndProcessRequest(System.IAsyncResult result);
}
事实上,mvc 和webAPI 没有太大的区别在框架上,他们的上层都是一个http 处理程序,主要不同的地方在于 MvcRouteHandler 实现IHttpAsyncHandler,而HttpControllerHandler 实现HttpTaskAsyncHandler
public class HttpControllerHandler : HttpTaskAsyncHandler
{
public HttpControllerHandler(RouteData routeData);
public HttpControllerHandler(RouteData routeData, HttpMessageHandler handler);
public override Task ProcessRequestAsync(HttpContext context);
}
public class Book
{
public int Id { get; set; }
public string Author { get; set; }
public string Title { get; set; }
}
public static class Books
{
public static List<Book> List = new List<Book>
{
new Book {Id = 1, Author = "ivan1", Title = "课程"},
new Book {Id = 2, Author = "ivan5", Title = "课程1"},
new Book {Id = 3, Author = "ivan3", Title = "课程2"},
new Book {Id = 4, Author = "ivan2", Title = "课程3"}
};
}
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
//注册特性路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
public class BooksController : ApiController // web api 是继承 ApiController
{
public Book GetById(int id)
{
var book = Books.List.FirstOrDefault(x => x.Id == id);
if (book == null) throw new HttpResponseException(HttpStatusCode.NotFound);
return book;
}
}
public class BooksController : Controller
{
public ActionResult Details(int id)
{
var book = Books.List.FirstOrDefault(x => x.Id == id);
if(book == null) return new HttpNotFoundResult();
return View(book);
}
public ActionResult Index()
{
return View(Books.List);
}
}
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);// 注册webapi路由
RouteConfig.RegisterRoutes(RouteTable.Routes);/ 注册mvc 路由
}
}
我们输入/api/books/{id} 会路由到webAPI
而/books/details/{id} 则是路由到 mvc