在Asp.net MVC 4.0中使用IHttpHandler

在MVC中,一般使用ControllerIController)对客户端的请求进行响应; 其实我们也可以使用IHttpHandler来接受请求和响应。

实现的方式非常简单,一共三步:

  1. 首先得定义一个类(例如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 }
  2. 定义一个类(例如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 }
  3. 在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 }

运行结果如下:

 

 

 

 

posted @ 2012-03-07 13:10  Rickey Hu  阅读(4393)  评论(4编辑  收藏  举报