abbas-h
abbas-h

Reputation: 450

.NET 8 Cors on Blazor web assembly standalone

I have Blazor web assembly standalone pProject in Visual Studio 2022.

enter image description here

enter image description here

Now when I want to use HttpClient and fetch some data from some website I get this error:

Access to fetch at 'https://tapi.bale.ai/someLink/getUpdates' from origin 'http://localhost:5246' 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.

How can I fix this CORS issue, and add header to host it?

i add Custome Header to IIS Express via applicationhost.config in .vs folder and now iis Express has header Access-Control-Allow-Origin=* but not working ..

enter image description here

Upvotes: 0

Views: 441

Answers (1)

Jason Pan
Jason Pan

Reputation: 21999

UPDATE

After investigation, if httpclient is used in the page to call third-party APIs, cross-domain problems will definitely occur.

So I recommend creating a proxy service, and the front-end page calls this service (providing url and verbs), and then this problem can be bypassed.

If tapi.bale.ai has other security certifications (such as CSRF), this solution may not work.

Here is the test code and result.

ProxyService.cs

using System.Net.Http.Json;

namespace BlazorApp1
{
    public class ProxyService
    {
        private readonly HttpClient _httpClient;

        public ProxyService(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        public async Task<string> SendRequestAsync(string url, string method, Dictionary<string, string> headers)
        {
            var proxyRequest = new ProxyRequest
            {
                Url = url,
                Method = method,
                Headers = headers
            };
            HttpResponseMessage response = null ;
            if (method == "GET") {
                response = await _httpClient.GetAsync(new Uri(url));
            }
            else if (method == "POST") {
                response = await _httpClient.PostAsJsonAsync("api/proxy", proxyRequest);
            }
           
            response.EnsureSuccessStatusCode();

            return await response.Content.ReadAsStringAsync();
        }
    }

    public class ProxyRequest
    {
        public string? Url { get; set; }
        public string? Method { get; set; }
        public Dictionary<string, string>? Headers { get; set; }
    }
}

Register it

enter image description here

Use it in Page

protected override async Task OnInitializedAsync()
{
    forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("sample-data/weather.json");

    var headers = new Dictionary<string, string>
    {
        { "User-Agent", "BlazorApp" }
    };

    result = await ProxyService.SendRequestAsync("https://localhost:7068/home/testcors1", "GET", headers);
}

enter image description here

If tapi.bale.ai is yours, you can follow below steps to add cors settings.

https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-8.0


Try to use BrowserRequestMode.NoCors and it works in my side.

var request = new HttpRequestMessage(HttpMethod.Get, "https://tapi.bale.ai/someLink/getUpdates");
request.SetBrowserRequestMode(BrowserRequestMode.NoCors);
var response = await Http.SendAsync(request);
//var content = await response.Content.ReadAsStringAsync();

enter image description here

Upvotes: 0

Related Questions