NamedClient没有给出预期的响应

时间:2019-07-17 18:12:02

标签: c# asp.net asp.net-core asp.net-web-api .net-core

我正在使用Named Client并将客户端创建为-

services.AddHttpClient("Clientname", client =>
{
    client.BaseAddress = new Uri(baseurl);
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Tokenvalue);
});

在控制器中:

public async Task<IActionResult> getApps()
{
    var request = new HttpRequestMessage(HttpMethod.Get, "apps");
    var client = _clientFactory.CreateClient("Clientname");
    var response = await client.SendAsync(request);

    return Ok(response);
}

以上实现给出了以下响应

{"version":{"major":1,"minor":1,"build":-1,"revision":-1,"majorRevision":-1,"minorRevision":-1},"content":{"headers":[{"key":"Content-Length","value":["86"]},{"key":"Content-Type","value":["application/json; charset=utf-8"]}]},"statusCode":404,"reasonPhrase":"Not Found","headers":[{"key":"Date","value":["Wed, 17 Jul 2019 17:49:13 GMT"]},{"key":"Server","value":["nginx"]},{"key":"X-Cascade","value":["pass"]},{"key":"X-Content-Type-Options","value":["nosniff"]},{"key":"X-Vcap-Request-Id","value":["ad5f538c-X-X-X-X::X-X-X-X-ef56283150cf"]}],"requestMessage":{"version":{"major":2,"minor":0,"build":-1,"revision":-1,"majorRevision":-1,"minorRevision":-1},"content":null,"method":{"method":"GET"},"requestUri":"https://api.example.io/apps","headers":[{"key":"Authorization","value":["Bearer Tokenvalue"]}],"properties":{}},"isSuccessStatusCode":false}

但是当我在没有指定客户端的情况下实现它时,可以使用Flurl-

在没有指定客户端的情况下进行植入
public async Task<IActionResult> getApps()
{
    var ul = Path.Combine(baseurl, "apps");

    return Ok(await ul.WithOAuthBearerToken(TokenValue).GetJsonAsync());
}

外部API的预期响应是JSON格式的应用列表。

我不确定自己在做什么,有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:2)

似乎您序列化了HttpResponseMessage而不是从中获取 actual JSON响应主体。您在第二种情况下使用的第三方库可能是通过GetJsonAsync()调用来完成的,这就是在这种情况下它起作用的原因。

无论如何,您都需要执行以下操作:

var json = await response.Content.ReadAsStringAsync();

那当然会让您的身体像弦一样。如果您想实际将JSON字符串反序列化为对象,则可以通过JsonConvert.DeserializeObject<T>运行值,也可以使用ReadAsAsync<T>