首页 > 解决方案 > 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 中执行任何操作。我在调试工具中也没有看到来自浏览器的网络流量来发送请求。有任何想法吗?

标签: c#flutter

解决方案


我想通了,我必须添加一个不同的库,因为 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;
  }

推荐阅读