忽略路由约束中的URL重写路径

时间:2016-07-01 14:42:12

标签: asp.net-web-api url-rewriting routes

我在WebAPI项目中定义了两个路由

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional },
           // constraint required so this route only matches valid controller names
            constraints: new { controller = GetControllerNames()}
        );

        // catch all route mapped to ErrorController so 404 errors
        // can be logged in elmah
        config.Routes.MapHttpRoute(
            name: "NotFound",
            routeTemplate: "{*path}",
            defaults: new { controller = "Error", action = "NotFound" }

        );

我的路线中有以下禁令

constraints: new { controller = GetControllerNames()}

方法实现如下

 private static string GetControllerNames()
    {
        var controllerNames = Assembly.GetCallingAssembly()
            .GetTypes()
            .Where(x =>
                x.IsSubclassOf(typeof(ApiController)) &&
                x.FullName.StartsWith(MethodBase.GetCurrentMethod().DeclaringType.Namespace + ".Controllers"))
            .ToList()
            .Select(x => x.Name.Replace("Controller", ""));

        return string.Join("|", controllerNames);
    }

现在问题是我的Web.Config文件中有一个Url Rewrite规则

<rewrite>
  <rules>
    <rule name="Proxy" stopProcessing="true">
      <match url="^publish/?(.*)" />
      <action type="Rewrite" url="http://someUrl.com/publish{R:1}" />
    </rule>
  </rules>
</rewrite>

此重写规则现在无效,我收到404错误。如何在约束中以某种方式忽略它。我尝试在Global.Asax中添加ignore但是没有用。

1 个答案:

答案 0 :(得分:1)

在Global.Asax中添加以下行并且它起作用了

RouteTable.Routes.Ignore("publish/{*pathInfo}");