4

HttpClient 如何在 Blazor Webassembly 中使用 HTTP 请求标头Sec-Fetch-Mode: no-cors发出请求?

我的实际代码是:

var hc = new HttpClient();
var responseHTTP = await hc.GetAsync("https://www.somedomain.com/api/");

但这会产生以下 HTTP 请求标头:

:authority: www.somedomain.com
:method: GET
:path: /api/json?input=test&key=AIzaSyDqWvsxxxxxxxxxxxxxxxxx1R7x2qoSkc&sessiontoken=136db14b-88bd-4730-a0b2-9b6c1861d9c7
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
origin: http://localhost:5000
referer: http://localhost:5000/places
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36
x-client-data: CJS2yQxxxxxxxxxxxxxxxxxxxxxxxxygEI7bXKAQiOusoBCObGygE=

4

1 回答 1

4

要具体回答您的问题,您需要创建HttpRequestMessage第一个。

例如

var request = new HttpRequestMessage(HttpMethod.Get, "https://www.somedomain.com/api/");
request.SetBrowserRequestMode(BrowserRequestMode.NoCors);  
request.SetBrowserRequestCache(BrowserRequestCache.NoStore); //optional            
using (var httpClient = new HttpClient())            
{
    var response = await httpClient.SendAsync(request);
    var content = await response.Content.ReadAsStringAsync();        
}

这将正确地将sec-fetch-mode标头设置为no-cors 我发现的结果,即使在 fiddler 中检查响应存在时,响应也会返回为空。
我最接近理解这个问题的是通过这个问题here,但不幸的是,这个错误已经关闭。

于 2020-11-29T21:08:37.527 回答