2015-09-29 36 views
1

我有一個繼承自ApiController的類,它的一些方法調用正確,其他一些方法是Not found。我找不到原因。我一直在尋找一個解決方案几個小時,現在仍然沒有得到它。請注意,我是新手,這是我在C#中的第一個WebApi。404在C#上找不到WebApi

路由:(WebApiConfig.cs)

public static class WebApiConfig 
    { 
     public static void Register(HttpConfiguration config) 
     { 
      // Configuration et services API Web 

      // Itinéraires de l'API Web 
      config.MapHttpAttributeRoutes(); 

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

控制器:

public class ExchangeController : ApiController 
{ 
    public HttpResponseMessage GetMailHeader(int id) 
    { 
     Console.WriteLine(id); 
     HttpResponseMessage response = new HttpResponseMessage(); 

     response.Content = new StringContent("ok"); 

     return response; 
    } 

    public HttpResponseMessage GetTest() 
    { 
     HttpResponseMessage response = new HttpResponseMessage(); 

     response.Content = new StringContent("working !!"); 

     return response; 
    } 
} 

JS:

$.ajax({ 
    type: "GET", 
    url: "/api/exchange/getTest", 
    done: function (data) { 
     console.log(data); 
    } 
}); 

$.ajax({ 
    type: "GET", 
    url: "/api/exchange/getMailHeader", 
    data: "42", 
    done: function (data) { 
     console.log(data); 
    } 
}); 

getTest該方法返回200 OKgetMailHeader返回404 Not Found。我錯過了什麼 ?

+0

平凡的一步,但我發現自己在無意中發現它:重建,那麼所有的解決方案重新部署。 – tomab

+3

getMailHeader的數據不正確。你應該這樣做:data:{id:42}(將它作爲JSON傳遞) –

+1

@Ahmedilyas這實際上是問題的一部分,它使我找到了解決方案! ;) – Elfayer

回答

0

感謝大家的意見和答案,它使我找到了解決方案。

我錯過了寫我的ajax請求。我沒有從console.log獲得控制檯上的任何打印數據,正如@Ahmedilyas所說,data屬性寫得很糟糕。

以下工作:

$.ajax({ 
    type: "GET", 
    url: "/api/exchange/getTest" 
}) 
.done(function (data) { 
    console.log(data); 
}); 

$.ajax({ 
    type: "GET", 
    url: "/api/exchange/getMailHeader", 
    data: { id: 42 } 
}) 
.done(function (data) { 
    console.log(data); 
}); 
3

據我所知,數據增加了一個查詢字符串,而不是url本身的一部分。您將id定義爲url的一部分,因此正確的url爲/ api/exchange/getmailheader/42。 您也可以將id移出routeTemplate。

+0

我一直保留路由的{{id}',因爲我不知道如何在執行'GET'方法時向其他任何方式發送額外的數據。雖然我可能只是刪除它,如果我可以從ajax'data'屬性發送所需的所有數據。 – Elfayer

0

由於您的方法以'Get'開頭,並且沒有特定的屬性,因此框架假定其爲HttpGet(請參閱下面的規則2),這需要id成爲url的一部分(基於默認路由)。

如果你希望它是一個HttpPost(你的身體傳遞一個JSON對象,像你現在正在做的),然後添加一個[HttpPost]屬性的方法上面或刪除動作名稱的「獲取」部分

Reference

HTTP方法。

  1. 可以與屬性指定HTTP方法:該框架僅如下選擇確定匹配請求的 HTTP方法的動作,AcceptVerbs, HttpDelete,HTTPGET,HttpHead,HttpOptions,HttpPatch,HttpPost,或 HttpPut。
  2. 否則,如果控制器方法的名稱以「Get」,「Post」,「Put」,「Delete」,「Head」,「Options」或「Patch」開頭,那麼按照慣例,那個HTTP方法。
  3. 如果以上都不是,則該方法支持POST。