您的位置:首页 > 理论基础 > 计算机网络

asp.net mvc 5.0 借助路由规则实现*.aspx与HttpHandler交互

2015-08-17 14:47 543 查看
实现效果是通过访问http://localhost/ajax.aspx执行ashx文件,原本打算使用httphandler在webconfig中的配置实现,但不知道是程序环境问题还是我个人资质有限,不是404就是500,在网上找了很多资料,结合国际友人的博客帮助,才完成了想要的效果,上代码:

需要几个文件:

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,看看效果吧


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: