在Asp.net MVC 4.0中使用IHttpHandler

在MVC中,一般使用Controller(IController)对客户端的请求进行响应; 其实我们也可以使用IHttpHandler来接受请求和响应。
实现的方式非常简单,一共三步:
首先得定义一个类(例如PlainHttpHandler),并实现IHttpHandler接口;
  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接口;
  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;
  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 <a href="http://go.microsoft.com/?LinkId=9394801" target="_blank">http://go.microsoft.com/?LinkId=9394801</a>  
  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.  }  

运行结果如下:
Highslide JS
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值