Asp.net-Mvc-5

web api 2 區域路由

  • May 11, 2017

我正在使用 asp.net mvc 5 和 web api 2。對於 asp.net mvc 5 項目,我一切正常……但是新的我正在嘗試添加 web api 2 路由……當我使用區域時。

我有 web api 2 控制器在項目根目錄工作:

//this is working 
  namespace EtracsWeb.Controllers
   {
       public class TestController : ApiController
       {
           //localhost:port/api/test ...this is working
           [HttpGet]
           public HttpResponseMessage Get()
           {

               return new HttpResponseMessage()
               {
                   Content = new StringContent("GET: Test message")
               };
           }

       }
   }

所以我假設 my Global.asax, myrouteconfig.cs和 mywebapiconfig.cs是正確的……(未顯示)……

但現在我正試圖讓我的 AREAS 中的 web api 2 工作……

我已經閱讀了我在網上可以找到的所有內容,這似乎應該可以工作:

namespace EtracsWeb.Areas.WorkOrder
{
   public class WorkOrderAreaRegistration : AreaRegistration
   {
       public override string AreaName
       {
           get
           {
               return "WorkOrder";
           }
       }

       public override void RegisterArea(AreaRegistrationContext context)
       {

           context.Routes.MapHttpRoute(
                   name: "AuditModel_Api",
                   routeTemplate: "WorkOrder/api/AuditModelApi/{id}",
                   defaults: new { id = RouteParameter.Optional }
               );

       //default
           context.Routes.MapHttpRoute(
                   name: "WorkOrder_Api",
                   routeTemplate: "WorkOrder/api/{controller}/{id}",
                   defaults: new { id = RouteParameter.Optional }
               );

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

我的控制器程式碼是:

namespace EtracsWeb.Areas.WorkOrder.ApiControllers
{
   public class AuditModelApiController : ApiController
   {
       IManufacturerStopOrderModelService auditModelService = new WorkOrder.Services.VWAuditModelService(UserSession.EtracsUserID, UserSession.ProgramID, UserSession.EtracsSessionID, UserSession.ConnectionString);

       [HttpGet]
       [Route("AuditModelApi")]
       public HttpResponseMessage Get()
       {

           return new HttpResponseMessage()
           {
               Content = new StringContent("GET: Test message")
           };
       }

       [Route("AuditModelApi/AuditModels")]
       public IEnumerable<VwAuditModel1> GetAuditModels()
       {
               return auditModelService.GetModels();
       }

       public IHttpActionResult UpdateAuditMode()
       {
           //example of what can be returned ... NotFound, Ok ... look into uses...

           VwAuditModel1 result = new VwAuditModel1();
           return Ok(result);

           return NotFound();
       }
   }
}

我已經嘗試過使用和不使用屬性命名的控制器[Route]……但我無法開始工作……

兩個簡單的案例

   public HttpResponseMessage Get()

和“真實”的案例

 public IEnumerable<VwAuditModel1> GetAuditModels()

返回相同的結果。在瀏覽器中,使用

http://localhost:64167/WorkOrder/api/AuditModelApi

http://localhost:64167/WorkOrder/api/AuditModelApi/AuditModels

我得到以下資訊:

<Error>
<Message>
No HTTP resource was found that matches the request URI 'http://localhost:64167/WorkOrder/api/AuditModelApi/AuditModels'.
</Message>
<MessageDetail>
No route providing a controller name was found to match request URI 'http://localhost:64167/WorkOrder/api/AuditModelApi/AuditModels'
</MessageDetail>
</Error>

您需要從對像中獲取HttpConfiguration實例GlobalConfigurationMapHttpAttributeRoutes()從.RegisterArea()``AreaRegistration.cs

   public override void RegisterArea(AreaRegistrationContext context) 
   {
       GlobalConfiguration.Configuration.MapHttpAttributeRoutes();

       //... omitted code  
   }

最後你必須在WebApiConfigremoveconfig.MapHttpAttributes()方法中,否則你會得到重複的異常。

public static class WebApiConfig
{
   public static void Register(HttpConfiguration config)
   {
       // Web API configuration and services
       config.EnableCors();

       // Configure Web API to use only bearer token authentication.
       config.SuppressDefaultHostAuthentication();
       config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));


       // Web API routes
       //config.MapHttpAttributeRoutes();

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

首先,你應該用它所屬的 Area 註冊路由,這才有意義,所以在你的AreaNameAreaRegistration類中一定要添加using System.Web.Http,這樣你就可以得到擴展方法MapHttpRoute,它不是System.Web.Mvc.

上面的命令有點偏離,導致 404。添加以下路由:

context.Routes.MapHttpRoute(
           name: "AreaNameWebApi",
           routeTemplate: "api/AreaName/{controller}/{id}",
           defaults: new { id = RouteParameter.Optional }
       );

如果您想花哨並從屬性中附加區域名稱AreaName(當然您關心良好的編碼實踐;)):

context.Routes.MapHttpRoute(
           name: "AreaNameWebApi",
           routeTemplate: string.Concat("api/", AreaName, "/{controller}/{id}"),
           defaults: new { id = RouteParameter.Optional }
       );

這將糾正 404 問題。預設情況下,在 Web API 模組中,它首先掃描“api”以確定在哪裡查找控制器(否則會混淆,這不是魔術),因此在動態附加區域名稱和控制器時需要首先使用 api。當然,您可以通過硬編碼路由來更改此順序,但我不建議這樣做,因為您需要在路由配置中提供每個路由和每個控制器,或者使用RouteAttribute.

另外,首先使用“api”,它將為您和您的使用者創建一個漂亮的標準 URL,而不是到處都有 API。以下是一些範例:

http://site/api/members/myAccount/update
http://site/api/members/myAccount/get/12345
http://site/api/members/contacts/getByOwnerId/12345

希望這可以幫助!

澤夫

引用自:https://stackoverflow.com/questions/29125412