【发布时间】:2021-03-31 18:08:13
【问题描述】:
在此 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}";
}
}
}
【问题讨论】:
-
真正的问题是服务器对
ws/run/reservations.json路由的OPTIONS 请求响应为403。 CORS 消息只是该问题的副作用。 -
“CORS 消息只是那个问题的副作用”你是什么意思? “用于 OPTIONS 请求的 403”是“预检”过程的一部分,所有这些都描述了浏览器和服务器之间的通信,并且是 CORS 的一部分。 CORS 消息绝对不是问题的副作用,而是问题本身。
标签: c# cors blazor basic-authentication preflight