尝试获取资源时出现 Blazor WASM NetworkError。 "CORS Missing Allow Origin"

Blazor WASM NetworkError when attempting to fetch resource. "CORS Missing Allow Origin"

在这个 Blazor WASM 应用程序中,我只是想使用第三方 API - 我打开开发人员工具并在尝试检索数据时看到这条消息“CORS Missing Allow Origin”。在这种情况下,我确实将 request.Headers.Add("Access-Control-Allow-Origin", "*"); 添加到请求中,但它仍然失败。我已经在除 FF 之外的不同浏览器中验证了这个结果。

Index.Razor 页面的代码在这里:

@page "/"
@inject HttpClient Http
<h3>Presentations Scheduled</h3>

<form>
    <fieldset class="form-group">
        <div>
            <button type="button" class="btn btn-dark mr-sm-2 mb-2"
                    @onclick=@(async ()=>  await GetToday())>
                Today
            </button>
        </div>
    </fieldset>

    @if (string.IsNullOrWhiteSpace(errorString) == true)
    {
        <div class="h2">No Data</div>
    }
    else if (string.IsNullOrWhiteSpace(errorString) == false)
    {
        <div class="h2">@errorString</div>
    }
</form>

<div class="h2">@TestReturn</div>




@code
{
    TestModel TestReturn;
    string errorString = null;
    string TestBaseURL;
    HttpRequestMessage request;

    private async Task GetToday()
    {
        var byteArray = Encoding.ASCII.GetBytes("user:pass");
        Http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

        string todayDate = DateTime.Today.AddDays(0).ToString("yyyyMMdd");
        TestBaseURL = "https://webservices.xcompany.com/";
        UriBuilder TestURI = new UriBuilder(TestBaseURL);
        TestURI.Scheme = "https";
        TestURI.Path = "ws/run/reservations.json";
        TestURI.Query = "resource_query_id=246492";
        var TestQuery = HttpUtility.ParseQueryString(TestURI.Query);
        TestQuery["scope"] = "extended";
        TestQuery["start_dt"] = todayDate;
        TestQuery["end_dt"] = todayDate;
        TestURI.Query = TestQuery.ToString();
        TestBaseURL = TestURI.ToString();
        request = new HttpRequestMessage(HttpMethod.Get, TestBaseURL);
        request.Headers.Add("Access-Control-Allow-Origin", "*");

        try
        {
            using var httpResponse = await Http.SendAsync(request);
            TestReturn = await httpResponse.Content.ReadFromJsonAsync<TestModel>();
        }
        catch (Exception ex)
        {
            errorString = $"There was a problem: {ex.Message}";
        }

    }

}

In this case I did add request.Headers.Add("Access-Control-Allow-Origin", "*");

你不添加这样的header。在这方面你实际上什么也没做。是第三方服务器要加这个header,不是你

CORS 是一种安全功能,定义如下:

Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate (by using such a header as "Access-Control-Allow-Origin", "*") any other origins (domain, scheme, or port) than its own from which a browser should permit loading of resources.

是您的浏览器不允许加载资源。据我所知,浏览器得到了数据的响应,但它没有加载它,而是告诉你它没有在响应中找到 header "Access-Control-Allow-Origin", "*",因此它拒绝加载资源。

解决方法: 请第三方 API 的人员将您添加到他们的 white-list 网站,以便可以从他们的网站访问资源。我想这对你来说不切实际。

由于 CORS 是一项 JavaScript 安全功能,并且仅在您进行 Fetch API 调用时才适用,因此您可以通过调用自己的 Web API 应该调用第三方 API,获取数据并将其传回您的 WebAssembly Blazor 应用程序。