2016-04-06 28 views
1

我想在Web API應用程序中調用外部託管的Web API。 嘗試使用Get()方法時,似乎一切正常。 然而,當我嘗試實施Get(int value)我得到一個錯誤:調用外部Web API時使用路徑'api/External'和方法'GET'進行多個操作

Multiple operations with path 'api/External' and method 'GET'.

什麼是錯我的控制器?

public class ExternalController : ApiController 
{ 
    static string _address = "http://localhost:00000/api/Values"; 
    private string result; 

    // GET api/values 
    public async Task<IEnumerable<string>> Get() 
    { 
     var result = await GetExternalResponse(); 

     return new string[] { result, "value2" }; 
    } 

    private async Task<string> GetExternalResponse() 
    { 
     var client = new HttpClient(); 
     HttpResponseMessage response = await client.GetAsync(_address); 
     response.EnsureSuccessStatusCode(); 
     var result = await response.Content.ReadAsStringAsync(); 
     return result; 
    } 

    public async Task<string> Get(int value) 
    { 
     var result = await GetExternalResponse(); 

     return result; 
    } 
} 

我也曾嘗試以下方法,這似乎也拋出了同樣的錯誤:當你做

private async Task<string> GetExternalResponse2(int value) 
{ 
    var client = new HttpClient(); 
    HttpResponseMessage response = await client.GetAsync(_address + "/" + value);    
    response.EnsureSuccessStatusCode(); 
    var result = await response.Content.ReadAsStringAsync(); 
    return result; 
} 

public async Task<string> Get(int value) 
{ 
    var result = await GetExternalResponse2(value); 

    return result; 
} 
+0

你如何使用你的第二個方法的參數值的方式?它沒有被傳遞給外部API是嗎? – cableload

+0

是的,你是對的,沒有被使用。我現在已經更新了我也試過的另一種方法。 – Richard

回答

1

你得到這樣

獲取API /外部/ {ID}

web api不確定是否調用不帶參數的Get方法或帶參數的Get方法,因爲在您的web api中定義的默認路由配置

我會建議使用屬性路由解決您的問題

[Route("api/External/Get")] 
    public async Task<IEnumerable<string>> Get() 

    [Route("api/External/Get/{id}")] 
    public async Task<string> Get(int value) 
+0

請參閱此討論,如果您想對默認路由進行更改http://stackoverflow.com/questions/15567945/defining-two-get-function-in-webapi – cableload

+0

謝謝。這有助於, – Richard

相關問題