Chinaunix首页 | 论坛 | 博客
  • 博客访问: 841962
  • 博文数量: 372
  • 博客积分: 10063
  • 博客等级: 中将
  • 技术积分: 4220
  • 用 户 组: 普通用户
  • 注册时间: 2012-02-24 11:36
文章分类

全部博文(372)

文章存档

2012年(372)

分类: 虚拟化

2012-03-07 16:39:03

在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("

    Hello, world!

    ");
    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
    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 }

运行结果如下:

阅读(421) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~