ASP.NET 自定义路由 RouteBase

适用场景:当前项目有一个接口:http://xxx.com/a.aspx,现在我们在不需要a.aspx这个文件的,直接处理这个地址的请求,我们可以做很多的事情,比如,直接返回一个静态的JSON文件内容。

Global.asax全局配置文件添加路由表的注册

      protected void Application_Start(object sender, EventArgs e)
        {
            RouteTable.Routes.Ignore("{resource}.axd/{*pathInfo}");
            RouteTable.Routes.RouteExistingFiles = true;
            RouteTable.Routes.Add("Stocks", new MyRoute());
        }

定制路由MyRoute 继承BouteBase

 public class MyRoute : RouteBase
    {
        public override RouteData GetRouteData(HttpContextBase httpContext)
        {

            //获取相对路径
            var virtualPath = httpContext.Request.AppRelativeCurrentExecutionFilePath;

            virtualPath = virtualPath.Substring(2).Trim('/');

            if (virtualPath.ToLower().Contains("a.aspx"))
            {
                string name = httpContext.Request["name"];

                var data = new RouteData(this, new MyRouteHandler());
                data.Values.Add("name", name ?? "test");
                return data;
            }

            //返回值为null,跳过此路由,进行下一个匹配
            return null;
        }

        public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
        {
      
            return null;
        }
    }

RouteHandler

   public class MyRouteHandler : IRouteHandler
    {
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            return new MyHttpHandler(requestContext);
        }
    }

HttpHandler 这里可以对Request请求做相应的业务处理

    public class MyHttpHandler : IHttpHandler
    {
        public RequestContext RequestContext { get; set; }

        public MyHttpHandler(RequestContext context)
        {
            RequestContext = context;
        }

        public void ProcessRequest(HttpContext context)
        {
            string name = RequestContext.RouteData.Values["name"].ToString();

            context.Response.ContentType = "application/json";
            context.Response.Charset = "utf-8";
            context.Server.Transfer("data.json");
            context.Response.End();
        }

        public bool IsReusable => false;
    }

也可以直接使用HttpHandler,在web.config文件里配置处理请求,方式多种。

 

posted @ 2016-11-10 11:46  阿弥陀佛呵呵哒  阅读(488)  评论(0编辑  收藏  举报