.Net: Google AI connector throws CORS error in Blazor WebAssembly app
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:
- Create a Blazor WebAssembly project in VS2022 17.9
- Add Microsoft.SemanticKernel.Connectors.Google package
- Call the Google Gemini API
- 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
This issue is stale because it has been open for 90 days with no activity.
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
Optionscall and with a NoContent result before.