How http request with "Sec-Fetch-Mode: no-cors" in Blazor Webassembly

8.3k Views Asked by At

How is it possible to make a request by HttpClient with the HTTP request header Sec-Fetch-Mode: no-cors in Blazor Webassembly?

My actuel code is :

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

But this produces the following HTTP request headers :

: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=

1

There are 1 best solutions below

2
johncyril On

To specifically answer your question, you need to create a HttpRequestMessage first.

e.g.

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

This will correctly set the sec-fetch-mode header to no-cors I've found however, that the response comes back as empty even though upon inspection in fiddler the response is there.
The closest I got to understanding the problem is through this issue here but unfortunately the bug was closed.