在MVC中,一般使用Controller(IController)對客戶端的請求進行響應; 其實我們也可以使用IHttpHandler來接受請求和響應。
實現的方式非常簡單,一共三步:
- 首先得定義一個類(例如PlainHttpHandler),並實現IHttpHandler接口;
View Code
1 using System.Web;
2 using System.Web.Routing;
3
4 namespace MvcMovie.Controllers
5 {
6 public class PlainHttpHandler : IHttpHandler
7 {
8 public bool IsReusable
9 {
10 get { return false; }
11 }
12
13 public void ProcessRequest(HttpContext context)
14 {
15 context.Response.Write( " <h1>Hello, world!</h1> ");
16 }
17 }
18 } - 定義一個類(例如PlainRouteHandler),並實現IRouteHandler接口;
View Code
1 using System.Web;
2 using System.Web.Routing;
3
4 namespace MvcMovie.Controllers
5 {
6 public class PlainRouteHandler : IRouteHandler
7 {
8
9 public IHttpHandler GetHttpHandler(RequestContext requestContext)
10 {
11 return new PlainHttpHandler();
12 }
13 }
14 } - 在Global.asax.cs的RegisterRoutes函數中,添加一個Route;指定匹配的url及IRouteHandler為PlainRouteHandler;
View Code
1 using System.Web.Mvc;
2 using System.Web.Routing;
3
4 namespace MvcMovie
5 {
6 // Note: For instructions on enabling IIS6 or IIS7 classic mode,
7 // visit http://go.microsoft.com/?LinkId=9394801
8
9 public class MvcApplication : System.Web.HttpApplication
10 {
11
12
13 public static void RegisterRoutes(RouteCollection routes)
14 {
15 routes.IgnoreRoute( " {resource}.axd/{*pathInfo} ");
16
17 // PlainRouteHandler implements IRouteHandler which returns a custom IHttpHandler (PlainHttpHandler)
18 routes.Add( new Route( " {controller} ", new MvcMovie.Controllers.PlainRouteHandler()));
19
20 routes.MapRoute(
21 name: " Default ",
22 url: " {controller}/{action}/{id} ",
23 defaults: new { controller = " Home ", action = " Index ", id = UrlParameter.Optional }
24 );
25 }
26
27 protected void Application_Start()
28 {
29 AreaRegistration.RegisterAllAreas();
30
31 RegisterRoutes(RouteTable.Routes);
32 }
33 }
34 }
運行結果如下:

