semantic-kernel icon indicating copy to clipboard operation
semantic-kernel copied to clipboard

.Net: Google AI connector throws CORS error in Blazor WebAssembly app

Open AshD opened this issue 1 year ago • 1 comments

Describe the bug Tested the Microsoft.SemanticKernel.Connectors.Google alpha nuget package with a WPF app and it works fine :-) Using it in a Blazor WebAssembly project throws a CORS error. CC @Krzysztof318

To Reproduce Steps to reproduce the behavior:

  1. Create a Blazor WebAssembly project in VS2022 17.9
  2. Add Microsoft.SemanticKernel.Connectors.Google package
  3. Call the Google Gemini API
  4. Throws CORS error - has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Expected behavior Call would succeed since Google Gemini Javascript library works. https://ai.google.dev/tutorials/get_started_web

Platform Blazor WebAssembly .Net 8

AshD avatar Apr 17 '24 19:04 AshD

This issue is stale because it has been open for 90 days with no activity.

github-actions[bot] avatar Jul 18 '24 01:07 github-actions[bot]

To solve this problem, you probably need to create a custom httphandler providing the extra header needed for CORS to be accepted.

i.e:

public class CorsMessageHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        // Process the request
        var result = await base.SendAsync(request, cancellationToken);

        // Add CORS headers lovingly to all responses
        result.Headers.Add("Access-Control-Allow-Origin", "https://example.com");
        result.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        result.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization");
        result.Headers.Add("Access-Control-Allow-Credentials", "true");

        return result;
    }
}

[!NOTE] If that doesn't work a custom service might be needed to make double request considering the Options call and with a NoContent result before.

rogerbarreto avatar Nov 25 '24 17:11 rogerbarreto