MVC IgnoreRoute /?_escaped_fragment_= 继续使用 IIS ARR 进行反向代理

MVC IgnoreRoute /?_escaped_fragment_= to continue Reverse Proxy with IIS ARR

技术信息

场景

我有一个 AngularJS 单页应用程序 (SPA),我正在尝试通过外部 PhantomJS 服务进行预呈现。

我希望 MVC 的路由处理程序忽略路由 /?_escaped_fragment_={fragment},因此 request can be handled directly by ASP.NET 并因此传递给 IIS 来代理请求。

理论上

**我可能是错的。据我所知,自定义路由优先于注册 Umbraco 路由之前完成的路由。但是我不确定告诉 MVC 忽略路由是否也会阻止 Umbraco 处理该路由。

练习中

我试图忽略具有以下内容的路由:

尝试一:

routes.Ignore("?_escaped_fragment_={*pathInfo}");

这会引发错误:The route URL cannot start with a '/' or '~' character and it cannot contain a '?' character.

尝试二:

routes.Ignore("{*escapedfragment}", new { escapedfragment = @".*\?_escaped_fragment_=\/(.*)" });

这并没有导致错误,但是 Umbraco 仍然接收到请求并将我的根页面还给我。 Regex validation on Regexr.

问题

内置路由行为不考虑查询字符串。但是,路由是可扩展的,如果需要可以基于查询字符串。

最简单的解决方案是创建一个可以检测您的查询字符串的自定义 RouteBase 子类,然后使用 StopRoutingHandler 确保路由不起作用。

public class IgnoreQueryStringKeyRoute : RouteBase
{
    private readonly string queryStringKey;

    public IgnoreQueryStringKeyRoute(string queryStringKey)
    {
        if (string.IsNullOrWhiteSpace(queryStringKey))
            throw new ArgumentNullException("queryStringKey is required");
        this.queryStringKey = queryStringKey;
    }

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        if (httpContext.Request.QueryString.AllKeys.Any(x => x == queryStringKey))
        {
            return new RouteData(this, new StopRoutingHandler());
        }

        // Tell MVC this route did not match
        return null;
    }

    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
        // Tell MVC this route did not match
        return null;
    }
}

用法

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        // This route should go first
        routes.Add(
            name: "IgnoreQuery",
            item: new IgnoreQueryStringKeyRoute("_escaped_fragment_"));


        // Any other routes should be registered after...

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}