2012-10-26 49 views
0

我有一個WebApi項目,我正在嘗試向它添加一個區域。WebApi未找到區域

在向webapi項目和mvc4應用程序添加新區域時是否需要完成不同的工作?

我有一個簡單區域註冊等

public class MobileAreaRegistration : AreaRegistration 
{ 
    public override string AreaName 
    { 
     get 
     { 
      return "Mobile"; 
     } 
    } 

    public override void RegisterArea(AreaRegistrationContext context) 
    { 
     context.MapRoute(
      "Mobile_default", 
      "Mobile/{controller}/{action}/{id}", 
      new { action = "Index", id = UrlParameter.Optional } 

     ); 
    } 
} 

控制器等

public class BusinessDetailsController : BaseController 
{ 
    public string Index() 
    { 
     return "hello world"; 
    } 
    public HttpResponseMessage Get() 
    { 
     var data = new List<string> {"Store 1", "Store 2", "Store 3"}; 
     return Request.CreateResponse(HttpStatusCode.OK, data); 
    } 
} 

但是我永遠不能達到API。我是在做一些愚蠢的事情還是需要做一些額外的步驟?

回答

5

您的代碼註冊了Area的MVC路由,而不是Web API路由。

爲此,請使用MapHttpRoute擴展方法(您需要爲System.Web.Http添加using語句)。

public override void RegisterArea(AreaRegistrationContext context) 
    { 
     context.Routes.MapHttpRoute(
      name: "AdminApi", 
      routeTemplate: "admin/api/{controller}/{id}", 
      defaults: new { id = RouteParameter.Optional } 
     ); 

     context.MapRoute(
      "Admin_default", 
      "Admin/{controller}/{action}/{id}", 
      new { action = "Index", id = UrlParameter.Optional } 
     ); 
    } 

然而,部分其實並不支持開箱即用的處理ASP.NET Web API,如果你有兩個控制器具有相同的名稱(不管它們是否在不同的領域),你會得到一個異常。

爲了支持這種情況,您需要更改控制器的選擇方式。你會發現一篇文章涵蓋了如何做到這一點here