Richard Richard - 3 months ago 9
C# Question

Multiple operations with path 'api/External' and method 'GET' while calling an external Web API

I am trying to call an externally hosted Web API within my Web API Application.
While attempting to use Get () method, everything seems to work fine.
However, when I try to implement

Get(int value)
I am getting an error:


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


What is wrong with my Controller?

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;
}
}


I have also tried the below approach, which also seems to throw the same error:

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;
}

Answer

When you do your get like this

Get api/External/{id}

web api is not sure whether to call the Get Method with no parameter or the Get Method with Parameter because of the default routing defined in your web api config

I would suggest using attribute routing to fix your problem

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

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