2016-09-18 105 views
1

我一直在建立一個WebAPI,試圖路由到正確的方法與ActionName。它適用於我嘗試調用的其中一個方法,但另一個方法會得到404錯誤。WebAPI ActionName路由半工作

我的WebAPI配置文件:

public static void Register(HttpConfiguration config) 
    { 
     // Web API configuration and services 
     // 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}/{action}/{id}", 
      defaults: new { id = RouteParameter.Optional } 
     ); 
    } 

我的WebAPI控制器的方法被格式化爲這樣:

這第一個是工作之一:

[ActionName("postdb")] 
public IEnumerable<string[]> postDB(string id) 
{ ... 

這第二個沒有:

[ActionName("getquery")] 
public IEnumerable<string[]> getQuery(string tables) 
{ ... 

我他們都呼籲從角以同樣的方式(溫度是被作爲參數傳遞的字符串):

$http.post('api/Test/postdb/' + temp).then(function (response) { ... 

$http.get('api/Test/getquery/' + temp).then(function (response) { ... 

我已經試過兩個行爲的改變名稱,第一個不管名字都起作用,第二個不管名字都不起作用。我也嘗試重新排序它們,在GET和POST之間切換,並更改參數。

有什麼建議嗎?

回答

2

不知道你爲什麼使用ActionName來設置路由?

您應該正在查看Route屬性。例如。

[HttpPost] 
[Route("postdb")] 
// Action doesn't have to be called 'postdb' 
public IEnumerable<string[]> postDB(string id) 

ActionName通常用於不同的目的(Purpose of ActionName

不過,我覺得奇怪的東西在你的例子是怎麼回事 - 我想設置ActionName不應該存在影響路由。爲了調試,我建議設置失敗的請求追蹤來查看請求未能到達動作的哪一點。

這些是在的WebAPI行動選擇(http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection

  1. 您可以用屬性指定HTTP方法的基本規則:AcceptVerbs,HttpDelete,HTTPGET,HttpHead,HttpOptions,HttpPatch,HttpPost,或HttpPut。如果控制器方法的名稱以「Get」,「Post」,「Put」,「Delete」,「Head」,「Options」或「Patch」開頭,那麼按照約定,動作支持該HTTP方法。

  2. 如果以上都不是,則該方法支持POST。

所以,在你的榜樣postdb方法可能地圖POST方法。但是可能是,因爲它的小寫ASP。NET不喜歡這樣,並應用規則3 - 如果您真的想使用ActionName(無論出於何種原因)而不是Route,請嘗試ActionName("PostDB")[ActionName("GetQuery")]

+0

謝謝你的建議。我會努力改變它! – user6846524

0

參數tables在第二個動作

[ActionName("getquery")] 
public IEnumerable<string[]> getQuery(string tables) 
{ ... 

的名稱不匹配的路由參數id名稱:

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