2012-11-20 31 views
5

我有一个添加了elmah的MVC4项目。我的Global.asax中的的Application_Start()有如何忽略MVC4 WebAPI配置中的路由?

WebApiConfig.Register(GlobalConfiguration.Configuration); // #1 
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
RouteConfig.RegisterRoutes(RouteTable.Routes); // #2 

#1和#2如下

public static class WebApiConfig 
{ 
    public static void Register(HttpConfiguration config) 
    { 
     config.Routes.MapHttpRoute(
      name: "DefaultApi", 
      routeTemplate: "{controller}/{action}/{id}", 
      defaults: new { id = RouteParameter.Optional }); 
    } 
    ... 
} 

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

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

的模板是相同的,路由到控制器的工作原理完全一样,我们希望它(从一个URI规范透视)。问题是在添加WebAPI路由之后添加忽略路由。因此,MVC4s路由应该忽略并由Elmah处理的内容(例如/elmah.axd/styles)被WebAPI拦截,请求失败=>因此我的elmah.axd页面没有CSS。我尝试翻转global.asax中的#1和#2,但导致所有的WebAPI路由失败 - FAR比CSS在Elmah中更糟糕!

我基本上需要一些方法来指示WebAPI的路由忽略{resource}.axd/{*pathInfo}正确的第一条路线 - 我该怎么做?

+0

您的Web API DefaultApi路线看起来很奇怪:它应该是这样的'routeTemplate: “API/{控制器}/{行动}/{ID}”,'否则MVC和的WebAPI路线将发生冲突。你有没有测试过常规控制器和API控制器正在为你工作? – nemesv

+0

我特别删除了'api'前缀,因为那会搞砸我们发布的URI。 MVC和WebAPI控制器都能正常工作 - 首先搜索WebAPI控制器,然后搜索MVC控制器(因为这是我设置配置的顺序) – DeepSpace101

+1

config.Routes.IgnoreRoute(“{resource} .axd/{* pathInfo} “);在WebApiConfig类中,方法Register。你试过了吗? – Regfor

回答

8

这是为我们工作 - 移动忽略了包装的和第一个。

protected void Application_Start() 
    { 
     AreaRegistration.RegisterAllAreas(); 

     //ignore route first 
     RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

     WebApiConfig.Register(GlobalConfiguration.Configuration); 
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
     // And taken out of the call below 
     RouteConfig.RegisterRoutes(RouteTable.Routes); 
     BundleConfig.RegisterBundles(BundleTable.Bundles); 
    } 
+0

由于您在注册WebApi之前设置路由配置,因此它看起来很有效。你能详细了解这里发生了什么吗? – tam

2

听起来就像你需要更好地控制路径定义的顺序。相反,从个人RouteConfig和WebApiConfig类拉动这些的,你可以在Global.asax.cs中像这样定义这些直接:

RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

GlobalConfiguration.Configuration.Routes.MapHttpRoute(
    name: "DefaultApi", 
    routeTemplate: "{controller}/{action}/{id}", 
    defaults: new {id = RouteParameter.Optional}); 

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

我在发布之前已经尝试过了:'我尝试了在global.asax中翻转#1和#2,但是这导致所有WebAPI路由失败 - 远比CSS在Elmah中工作的更差# – DeepSpace101

+0

啊,你是对的!我已更新我的答案以解决此问题。 –