ASP.NET MVC 利用 IHttpModule 实现路由调试

在实际的项目中,会存在大量的自定义路由,URL 很容易被错误的路由捕获,现在我们就实现一个这样的诊断工具,该工具通过实现一个自定义的 IHttpModule 来实现。

首先,我们创建 CustomRouteHandler:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public class CustomRouteHandler : IRouteHandler
{
    public IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        if (HasQueryStringKey("routeInfo", requestContext.HttpContext.Request))
        {
            OutputRouteDiagnostics(requestContext.RouteData, requestContext.HttpContext);
        }
 
        var handler = new CustomMvcHandler(requestContext);
        return handler;
    }
 
    private bool HasQueryStringKey(string keyToTest, HttpRequestBase request)
    {
        return Regex.IsMatch(request.Url.Query, string.Format(@"^\?{0}$", keyToTest));
    }
 
    private void OutputRouteDiagnostics(RouteData routeData, HttpContextBase context)
    {
        var response = context.Response;
        response.Write(
            @"<style>body {font-family: Arial;}
                     table th {background-color: #359; color: #fff;}
              </style>
        <h1>Route Data:</h1>
        <table border='1' cellspacing='0' cellpadding='3'>
            <tr><th>Key</th><th>Value</th></tr>");
        foreach (var pair in routeData.Values)
        {
            response.Write(string.Format("<tr><td>{0}</td><td>{1}</td></tr>", pair.Key, pair.Value));
        }
        response.Write(
            @"</table>
            <h1>Routes:</h1>
            <table border='1' cellspacing='0' cellpadding='3'>
                <tr><th></th><th>Route</th></tr>");
 
        bool foundRouteUsed = false;
        foreach (Route r in RouteTable.Routes)
        {
            response.Write("<tr><td>");
            bool matches = r.GetRouteData(context) != null;
            string backgroundColor = matches ? "#bfb" : "#fbb";
            if (matches && !foundRouteUsed)
            {
                response.Write("»");
                foundRouteUsed = true;
            }
            response.Write(string.Format(
                "</td><td style='font-family: Courier New; background-color:{0}'>{1}</td></tr>",
                backgroundColor, r.Url));
        }
 
        response.End();
    }
}

CustomRouteHandler 中使用到了一个 CustomMvcHandler,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class CustomMvcHandler : MvcHandler
{
    public CustomMvcHandler(RequestContext requestContext)
        : base(requestContext)
    {
    }
 
    protected override void ProcessRequest(HttpContext httpContext)
    {
        try
        {
            base.ProcessRequest(httpContext);
        }
        catch (Exception exc)
        {
            throw new ApplicationException("RouteUsed:" +
                   RequestContext.RouteData.Route.GetVirtualPath(
                    RequestContext, RequestContext.RouteData.Values), exc);
        }
    }
}

其次,我们需要在 MapRoute的 时候指定 CustomRouteHandler。

1
2
3
4
5
routes.MapRoute (
    "Default", // Route name
    "Home/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
).RouteHandler = new CustomRouteHandler ();

如果我们想要看当前URL的路由信息,则输入 URL 如:http://localhost:8080/Home?routeInfo,就会显示路由信息了。

posted @   Charles Zhang  阅读(1978)  评论(1编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示