.NET Core 2.1 的 HttpClient 没有返回预期的值。

4
我将使用界面调用此URL的API http://localhost:55260/api/Accounts/GetList
这是它所引用的控制器:
[HttpGet]
[Route("GetList")]
[AllowAnonymous]
public ActionResult<IEnumerable<string>> GetList()
{
    return new string[] { "value1", "value2" };
}

然而,我得到的不是字符串返回值,而是这个:

enter image description here

这是我声明httpclient/interface的方式:
private readonly HttpClient httpClient;
public AuthenticationClient(HttpClient httpClient)
{
    httpClient.BaseAddress = new Uri("http://localhost:55260/api/Accounts");
    httpClient.DefaultRequestHeaders.Accept.Clear();
    httpClient.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));
    this.httpClient = httpClient;
}

public async Task<IEnumerable<string>> GetDataAsync()
{
    List<string> result = null;
    HttpResponseMessage response = await httpClient.GetAsync("/GetList");
    if (response.IsSuccessStatusCode)
    {
        result = await response.Content.ReadAsAsync<List<string>>();
    }
    return result;
}

我已经在我的Startup.cs中声明了它,使用services.AddHttpClient();

这是我调用接口的方式

private readonly IAuthenticationClient authenticationClient;
public HomeController(IAuthenticationClient authenticationClient)
{
    this.authenticationClient = authenticationClient;
}

public IActionResult Index()
{
    var result = authenticationClient.GetData();
    return View();
}

我是否错过了什么或者有关于如何使用HttpClients的教程?另外,我该如何通过它来发布数据?


"有没有关于如何使用HttpClients的教程?" ==> https://learn.microsoft.com/zh-cn/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client - jazb
首先确保您的控制器顶部有一个基本的 [Route(“account”)],这样操作 Route(“GetList”)将不会在根目录/api/Getlist上执行,或者更好的方法是使用 [HttpGet(“GetList”)] 并删除操作方法上的路由修饰。 - Ahmed HABBACHI
3个回答

4

您的接口定义了一个异步调用。换句话说,“GetData”返回Task<string>而不是实际值。

为了获取实际值,请尝试以下方法(手写代码,未经调试)

public async Task<IActionResult> Index()
{
    var result = await authenticationClient.GetData();
    return View(result);
}

抱歉,我根据您给我的初始链接更新了我的问题。我也改变了我的索引,使其看起来像您的,但现在我得到了null作为结果。 - JianYA

0

当我更改控制器代码时,我就能做到这一点

public async Task<IActionResult> Index()
    {
        var result = await _authenticationClient.GetDataAsync();
        return View();
    }

修改GetDataAsync()

HttpResponseMessage response = await httpClient.GetAsync("/api/Accounts/GetList");

0

ASP.NET Core 2.1 包含了一个新的 IHttpClientFactory 服务,使得在应用中配置和使用 HttpClient 实例更加容易。 HttpClient 已经具有委托处理程序的概念,可以将它们链接到出站 HTTP 请求中。这个工厂:

  • 使得按命名客户端注册 HttpClient 实例更直观。
  • 实现了 Polly 处理程序,允许使用 Retry、CircuitBreakers 等 Polly 策略。

更多信息请参阅 发起 HTTP 请求


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接