[Asp .Net MVC][WebAPI] WebAPI route attribute 回傳 404 ( Attribute based webapi2 always routing returns 404 )

熱門文章 (Popular Post)

Posted by : Duran Hsieh 2016-03-20

問題

過去在某個ASP .Net MVC專案中,因為架構原因,決定要加入WebAPI Controller
進行後續的開發,卻發現使用 Route attribute、RoutePrefix attribute完全沒有效果,
結果不斷呈現 Http 404 - file or directory not found找不到檔案或目錄 ) 畫面。







花了些許時間,最後才發現原因所在!!!


解決方法(solution)

在Global.asax.cs中,MapHttpAttributeRoutes()必須要在任何Routes.MapHttpRoute()前面。
Route Attribute才會有作用,否則會被擋掉!
專案中的 WebApiConfig.cs 與 RouteConfig.cs 皆有 Routes.MapHttpRoute() 方法。
但是MapHttpAttributeRoutes()寫在WebApiConfig.cs中,但WebApiConfig.cs卻在RouteConfig.cs後面。

In Global.asax.cs,  MapHttpAttributeRoutes() needs to be registered before any Routes.MapHttpRoute() is registered.
In my case, I have Routes.MapHttpRoute() in both WebApiConfig.cs and RouteConfig.cs
but RouteConfig.cs is registered before WebApiConfig.cs is register.







本篇文章同步發布於個人部落格與點部落。

參考資料

Stack Overflow - Attribute based webapi2 routing returns 404 for some methods
MS ASP .NET CodePlex - Attribute Routing in MVC and Web API



Leave a Reply

Subscribe to Posts | Subscribe to Comments

- Copyright © Duran Hsieh @ Duran 的技術冶煉廠 - Date A Live - Powered by Blogger - Designed by Johanes Djogan -