0

I'm working with a Blazor wasm ASP.Net Core Hosted app.

The following code returns STATUS 200 ok but the string content is empty.

I'm making the request from the client side on the OnInitializedAsync methode of a component.

string URLString = "https://www.bnr.ro/nbrfxrates.xml";

var request = new HttpRequestMessage(HttpMethod.Get, URLString);
request.SetBrowserRequestMode(BrowserRequestMode.NoCors);  
request.SetBrowserRequestCache(BrowserRequestCache.NoStore);     
HttpResponseMessage response = await Http.SendAsync(request);

string xmlData = await response.Content.ReadAsStringAsync();
Console.WriteLine(xmlData);

UPDATE

I've changed to BrowserRequestMode.Cors

string URLString = "https://www.bnr.ro/nbrfxrates.xml";

var request = new HttpRequestMessage(HttpMethod.Get, URLString);
request.SetBrowserRequestMode(BrowserRequestMode.Cors);    
HttpResponseMessage response = await Http.SendAsync(request);

string xmlData = await response.Content.ReadAsStringAsync();
Console.WriteLine(xmlData);

On Server side Program.cs i've added CORS

builder.Services.AddCors(options =>
{
    options.AddPolicy("NewPolicy", builder =>
     builder.AllowAnyOrigin()
                  .AllowAnyMethod()
                  .AllowAnyHeader());
});

...
app.UseCors("NewPolicy");

Now the request is blocked

Acccess to fetch at 'https://www.bnr.ro/nbrfxrates.xml' from origin 'https://localhost:7271' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. dotnet.7.0.4.fmdigzwz3p.js:5 GET https://www.bnr.ro/nbrfxrates.xml net::ERR_FAILED 200 (OK)

Radu Mihai
  • 55
  • 1
  • 2
  • 9

1 Answers1

0

request.SetBrowserRequestMode(BrowserRequestMode.NoCors);

In a no-cors mode, the response is opaque which means you cannot see any body content. See Trying to use fetch and pass in mode: no-cors and Fetch API default cross-origin behavior.

Luke Vo
  • 17,859
  • 21
  • 105
  • 181
  • I guess you're right, but if do it with cors I get No 'Access-Control-Allow-Origin' header is present on the requested resource. – Radu Mihai Apr 17 '23 at 18:40
  • 1
    @RaduMihai Yes it is by-design due to privacy and security. You can't just access other people's resources from browser. If you control the server (i.e. it's yours), you can add the CORS headers. If not, you have to find another way. – Luke Vo Apr 18 '23 at 02:52
  • @RaduMihai See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS – Luke Vo Apr 18 '23 at 02:54
  • Well it's not mine, it's the national bank of romania and there's no documentation about how to fetch the data... i guess the only option is to download the xml to my server. – Radu Mihai Apr 18 '23 at 06:35