在MVC中,一般使用Controller(IController)对客户端的请求进行响应; 其实我们也可以使用IHttpHandler来接受请求和响应。
实现的方式非常简单,一共三步:
首先得定义一个类(例如PlainHttpHandler),并实现IHttpHandler接口;
定义一个类(例如PlainRouteHandler),并实现IRouteHandler接口;
在Global.asax.cs的RegisterRoutes函数中,添加一个Route;指定匹配的url及IRouteHandler为PlainRouteHandler;
运行结果如下:
实现的方式非常简单,一共三步:
首先得定义一个类(例如PlainHttpHandler),并实现IHttpHandler接口;
- using System.Web;
- using System.Web.Routing;
- namespace MvcMovie.Controllers
- {
- public class PlainHttpHandler : IHttpHandler
- {
- public bool IsReusable
- {
- get { return false; }
- }
- public void ProcessRequest(HttpContext context)
- {
- context.Response.Write("<h1>Hello, world!</h1>");
- }
- }
- }
定义一个类(例如PlainRouteHandler),并实现IRouteHandler接口;
- using System.Web;
- using System.Web.Routing;
- namespace MvcMovie.Controllers
- {
- public class PlainRouteHandler : IRouteHandler
- {
- public IHttpHandler GetHttpHandler(RequestContext requestContext)
- {
- return new PlainHttpHandler();
- }
- }
- }
在Global.asax.cs的RegisterRoutes函数中,添加一个Route;指定匹配的url及IRouteHandler为PlainRouteHandler;
- using System.Web.Mvc;
- using System.Web.Routing;
- namespace MvcMovie
- {
- // Note: For instructions on enabling IIS6 or IIS7 classic mode,
- // visit <a href="http://go.microsoft.com/?LinkId=9394801" target="_blank">http://go.microsoft.com/?LinkId=9394801</a>
- public class MvcApplication : System.Web.HttpApplication
- {
- public static void RegisterRoutes(RouteCollection routes)
- {
- routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
- // PlainRouteHandler implements IRouteHandler which returns a custom IHttpHandler (PlainHttpHandler)
- routes.Add(new Route("{controller}", new MvcMovie.Controllers.PlainRouteHandler()));
- routes.MapRoute(
- name: "Default",
- url: "{controller}/{action}/{id}",
- defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
- );
- }
- protected void Application_Start()
- {
- AreaRegistration.RegisterAllAreas();
- RegisterRoutes(RouteTable.Routes);
- }
- }
- }
运行结果如下: