c# - Flutter - HttpClient 适用于应用程序,但不适用于浏览器。.NET Core 3.1 WebAPI + Flutter2
问题描述
我有一个非常简单的 WebAPI,它只是 .NET Core 3.1 的默认设置。我正在使用使用 .NET Core 自签名的证书。当我为使用 Flutter 2 构建的 macOS 发出网络请求时,一切正常。但是,如果我在 Chrome 中调试,它就不起作用。这是我正在使用的 Flutter 2 代码:
Future<int> getElements() async {
print("getting weatherforecast");
HttpClient client = new HttpClient();
client
.getUrl(Uri.parse("https://localhost:5001/weatherforecast"))
.then((HttpClientRequest request) {
// Optionally set up headers...
// Optionally write to the request object...
// Then call close.
return request.close();
}).then((HttpClientResponse response) {
// Process the response.
print(response.toString());
});
return 1;
}
API:
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = rng.Next(-20, 55),
Summary = Summaries[rng.Next(Summaries.Length)]
})
.ToArray();
}
我尝试添加打印消息,但它似乎没有在 httpclient 中执行任何操作。我在调试工具中也没有看到来自浏览器的网络流量来发送请求。有任何想法吗?
解决方案
我想通了,我必须添加一个不同的库,因为 HttpClient 不执行浏览器请求,所以我通过以下方式导入了 http_client:
flutter pub add http_client
然后将我的请求和导入更改为:
import 'package:http_client/browser.dart' as http;
...
Future<int> getElements() async {
print("getting weatherforecast");
http.BrowserClient client = new http.BrowserClient();
var rs = await client
.send(http.Request('GET', "https://localhost:5001/weatherforecast"));
final textContent = await rs.readAsString();
print(textContent);
return 1;
}
推荐阅读
- elasticsearch - 弹性 APM HTTP 错误 (503):队列已满
- python - 什么是错误“ImportError:numpy.core.multiarray 导入失败”?
- c - 如果语句为真,我如何只显示 printf 语句?
- ruby-on-rails - 正确提交参数时验证失败
- java - 引起:java.lang.IllegalArgumentException:未知实体:xxx
- mysql - MySQL:启用 LOAD DATA LOCAL INFILE 重置
- angular - 如何在 Angular Unviersal 项目的服务器上进行预渲染?
- azure - 没有免费/共享服务计划的选项
- python - 动态构建字典时的Python“关键错误”(动态)
- r - 如何动态访问数据框列表中的特定属性