【问题标题】:Multiple operations with path 'api/External' and method 'GET' while calling an external Web API调用外部 Web API 时使用路径“api/External”和方法“GET”进行多项操作
【发布时间】:2016-04-06 15:18:05
【问题描述】:

我正在尝试在我的 Web API 应用程序中调用外部托管的 Web API。 在尝试使用 Get () 方法时,一切似乎都正常。 但是,当我尝试实现 Get(int value) 时,我收到了一个错误:

使用路径 'api/External' 和方法 '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;
}

【问题讨论】:

  • 您如何在第二种方法中使用参数值?它没有被传递给外部api吗?
  • 是的,你说得对,那是没有被使用的。我现在更新了我也尝试过的另一种方法。

标签: c# .net asp.net-web-api async-await


【解决方案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) 

【讨论】:

猜你喜欢
  • 2012-09-28
  • 2019-05-26
  • 1970-01-01
  • 2017-04-19
  • 2021-02-08
  • 2013-11-26
  • 1970-01-01
  • 1970-01-01
  • 2020-05-27
相关资源
最近更新 更多