Blazor Webassembly-调用外部API

时间:2020-06-15 23:51:47

标签: httpclient blazor blazor-webassembly

我一直在尝试从Blazor客户端Web程序集中调用单独的asp.net核心Web api。我将模板Web API模板与此控制器一起使用。我在startup.cs中设置了CORS。我在Blazor客户端中使用标准的HTTP客户端。在本地运行,我可以在API代码上设置一个断点,然后看到它被击中。但是客户端抛出异常:输入错误

任何帮助将不胜感激。

大卫

[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }

    [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();
    }
}

Startup.cs
     services.AddCors(options =>
            {
                options.AddPolicy(name: MyAllowSpecificOrigins,
                                  builder =>
                                  {
                                      builder.WithOrigins("http://example.com",
                                                          "http://www.contoso.com")
                                                          .AllowAnyOrigin()
                                                          .AllowAnyMethod()
                                                          .AllowAnyHeader();
                                  });
            });

Blazor Client
var response = await Http.GetFromJsonAsync<WeatherForecast[]>("WeatherForecast");

1 个答案:

答案 0 :(得分:1)

我遇到了同样的错误,并且在使用开发人员工具控制台时,似乎不允许使用混合内容(HTTPS和HTTP)。混合内容:HTTPS加载了位于“ https://”的页面,但请求了不安全的资源“ http://”。该请求已被阻止;内容必须通过HTTPS提供。检查您的页面是否也是这种情况。