2016-08-23 35 views
1

我有5個項目:如何從htttp客戶端項目調用api控制器?

  • Students.BBL(類庫)
  • Students.DAL(類庫)
  • Students.WEB(MVC項目)
  • Students.Client(類庫, Web和API)
  • Students.API之間

我如何通過客戶端調用API控制器從WEB? 因爲當我從客戶端調用Home控制器(Web)方法時,它會轉到客戶端,在這裏我應該創建一個API請求。但是......

我不知道如何編寫正確的URL。 URL like like:

http://localhost:56543/api/students/4 

不起作用,它返回404錯誤。

代碼:

public StudentDTO find(int id) 
    { 
     try 
     { 
      HttpClient client = new HttpClient(); 
      client.BaseAddress = new Uri(Base_URL); 
      client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 
      HttpResponseMessage response = client.GetAsync("student/" + id.ToString()).Result; 

      if (response.IsSuccessStatusCode) 
       return response.Content.ReadAsAsync<CountryDTO>().Result; 
      return null; 
     } 
     catch 
     { 
      return null; 
     } 

私人字符串BASE_URL = 「http://localhost:56543/api/」;

+0

安置自己的代碼,使用HttpClient的。 –

+0

@WilliamXifaras修復問題 –

+0

你只需要嘗試類似http:// localhost:56543/apicontroller/method /可選 – Hackerman

回答

-1

你要定位的api的控制器名稱和方法名稱是什麼? 假設控制器名稱爲「YourControl」,動作名稱爲「YourAction」。 修改路線的配置如下:

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

還可以修改/檢查此,

HttpResponseMessage response = client.GetAsync("YourController/" + id.ToString()).Result; 
+0

「國家」是一個Api控制器的名稱 –

+0

和我的客戶端項目是一個類庫有isnt webapiconfig –

+0

使這個路由配置改變在api項目... –

0

從這些評論你在上述職位有:

  • API層:公共IHttpActionResult GetStudent (int id){stRepository.GetStById(id);返回Ok(stRepository.GetStById(id)); }

  • 「國家」是阿比控制器

的名字好像你的路線是錯誤的。 要解決的路線,你期望 - http://localhost:56543/api/students/4,你應該有
命名StudentsController

    • ApiController該控制器應該有有且僅有一個它接受一個id爲參數GET方法 - GetSomeMethodName( int id)。在你的情況下,你有GetStudent(int id)。確保你沒有任何其他GET方法在該簽名的控制器中。這一點假設你已經修改了默認的wep api route config。

    如果您的控制器名稱是「國家」,請嘗試http://localhost:56543/api/country/4。 如果您在國家/地區控制器中使用上述簽名執行多個GET操作,則會再次出現錯誤。

    廣東話解決您的問題,除非你顯示你的API控制器代碼

    在情況下,你仍然想使用國家控制器本身,你必須在該控制器的多GET方法,那麼我會建議屬性的路由。

    在網頁API的配置,補充一點:

    config.MapHttpAttributeRoutes(); 
    

    而在你的API控制器動作

    [HttpGet] 
    [Route("~api/students/{id}")] 
    public IHttpActionResult GetStudent(int id) 
    { 
        stRepository.GetStById(id); 
        return Ok(stRepository.GetStById(id)); 
    } 
    

    通過上述配置,則在路由http://localhost:56543/api/students/4得到斯圖登細節 - 嘗試打這個保持API項目運行後,瀏覽器的URL。

    但我強烈建議你有學生控制器而不是在國家控制器來獲得學生的詳細信息

  • 相關問題