Search code examples
google-cloud-functionsblazor-webassembly

Calling Google Cloud Function from Blazor WASM


I am trying to call my Google Cloud Function from my Blazor WASM App, but I get this error:

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100] Unhandled exception rendering component: TypeError: Failed to fetch System.Net.Http.HttpRequestException: TypeError: Failed to fetch ---> System.Runtime.InteropServices.JavaScript.JSException: TypeError: Failed to fetch at System.Net.Http.BrowserHttpHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)

If I enter the url https://us-central1-<PROJECT_ID>.cloudfunctions.net/CloudFunctions directly into the browser everything works well. The curl command curl -Method POST https://us-central1-araberboerse-1337.cloudfunctions.net/CloudFunctions in my powershell works.

I also tried fetching a different api from my Blazor app, which also worked.

I can even see the request in the logs of my cloud functions in the Google Cloud Console with the response code 200.

The code I'm using in my Blazor app is as follows

public class FunctionsHelper
{
    private static readonly HttpClient client = new HttpClient() { };
           
    public static async Task SucheEinreichen(SucheRequest sucheRequest)
    {
        var response = await client.GetStringAsync("https://us-central1-<PROJECT_ID>.cloudfunctions.net/CloudFunctions");
    }
}

The Cloud Function code:

public class Function : IHttpFunction
{
    /// <summary>
    /// Logic for your function goes here.
    /// </summary>
    /// <param name="context">The HTTP context, containing the request and the response.</param>
    /// <returns>A task representing the asynchronous operation.</returns>
    public async Task HandleAsync(HttpContext context)
    {
        await context.Response.WriteAsync("Hello World!");
    }
}

What do I do wrong? I expect it to be a problem in my Blazor app since calling the Cloud Function elsewhere is no problem.


Solution

  • The solution was to enable CORS in the cloud function code to allow frond-end javascript code to access the endpoint.

    Mentioned in GCF reference

    Sample code