6

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=

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Fabianus
  • 633
  • 7
  • 16

1 Answers1

7

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.

johncyril
  • 113
  • 1
  • 7
  • 2
    This solution worked for my application. I used it to make a HEAD request to get the "Last-Modified" date in the header from a server where CORS was not enabled. The browser will not pass the content to your code even with NoCors enabled, but it's still useful if you only want to read the headers or test the connection. +1 – Yogi Dec 19 '21 at 08:15
  • 2
    Please be aware: You must first add the Microsoft.AspNetCore.Components.WebAssembly library, so that you have the "SetBrowserRequestMode" and the "SetBrowserRequestCache" methods available in the HttpRequestMessage. – Tom Feb 24 '23 at 08:48