asp.net mvc 5.0 借助路由规则实现*.aspx与HttpHandler交互
2015-08-17 14:47
543 查看
实现效果是通过访问http://localhost/ajax.aspx执行ashx文件,原本打算使用httphandler在webconfig中的配置实现,但不知道是程序环境问题还是我个人资质有限,不是404就是500,在网上找了很多资料,结合国际友人的博客帮助,才完成了想要的效果,上代码:
需要几个文件:
1.AjaxRouteHandler
2.AjaxHandler.ashx
3.RouteConfig的配置,特别要注意自定义的路由规则一定要在默认规则之前,不然会报404错误;如果需要指定文件,就写清楚文件名即可,如果只是需要过滤类型,在规则中的URL部分加上{}即可,例如:{ajax}.aspx,这样写的结果就是对所有后缀为aspx请求进行拦截
接下来在地址中敲入:http://localhost/ajax.aspx,看看效果吧
需要几个文件:
1.AjaxRouteHandler
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Routing; namespace Web.MVC.Models { public class AjaxRouteHandler : IRouteHandler { public System.Web.IHttpHandler GetHttpHandler(RequestContext requestContext) { return new Ajax.AjaxHandler(requestContext); } } }
2.AjaxHandler.ashx
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Routing; namespace Ajax { /// <summary> /// AjaxHandler 的摘要说明 /// </summary> public class AjaxHandler : IHttpHandler { public bool IsReusable { get { return false; } } protected RequestContext RequestContext { get; set; } public AjaxHandler() : base() { } public AjaxHandler(RequestContext requestContext) { this.RequestContext = requestContext; } public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Write("Hello World"); } //public bool IsReusable //{ // get // { // return false; // } //} } }
3.RouteConfig的配置,特别要注意自定义的路由规则一定要在默认规则之前,不然会报404错误;如果需要指定文件,就写清楚文件名即可,如果只是需要过滤类型,在规则中的URL部分加上{}即可,例如:{ajax}.aspx,这样写的结果就是对所有后缀为aspx请求进行拦截
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace Web.MVC { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); //******以下代码一定要在MapRoute之前,如果在其之后会报404错误******// Route r = new Route("ajax.aspx", new Web.MVC.Models.AjaxRouteHandler());//利用IRouteHandler实现请求拦截与转发 r.RouteExistingFiles = false;//设置检查文件是否存在 routes.Add(r);//加入路由规则 routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
接下来在地址中敲入:http://localhost/ajax.aspx,看看效果吧
相关文章推荐
- android 缓存网络音频播放
- jason解析
- 黑马程序员-Java基础:网络编程
- Ubuntu 网卡桥接及桥接后网络不通的解决方法
- 网络编程学习之TCP客户端与服务器端
- TCP/IP协议三次握手与四次握手流程解析
- cisco 动态路由RIP配置
- HttpURLConnection 乱码
- http://www.cnblogs.com/dudu/archive/2011/03/05/asp_net_webform_mvc.html
- 在android用Get方式发送http请求
- iscsi网络存储LVM逻辑卷和RAID5卷
- 高性能、高并发、高扩展性和可读性的网络服务器架构:StateThreads
- 网络加载时Dialog
- win10无线网卡WIFI出现卡顿网络延迟高该怎么办?
- HTTP Content-type
- HTTP 权威指南 阅读笔记
- UNIX网络编程卷一:第二十六章 线程
- Windows Socket 网络编程——第五章 操作模式
- 你所不知道的TCP/IP传输层
- Volley详解(五)——网络(Network)