Skip to content

Web Application Integration

Gunpal Jain edited this page Nov 15, 2026 · 4 revisions

Web Application Integration

The Google_GenerativeAI.Web package registers the SDK with the .NET dependency injection container. It adds IServiceCollection extension methods that bind GenerativeAIOptions, set up authentication, and register IGenerativeAiService, which you inject into controllers, minimal API handlers or other services.

The package targets net6.0 to net10.0 (plus net11.0) and netstandard2.0. It depends on Google_GenerativeAI and Google_GenerativeAI.Auth.

Installation

dotnet add package Google_GenerativeAI.Web

Registering the services

All overloads live in GenerativeAI.Web.ServiceCollectionExtension and register IGenerativeAiService as a transient service.

1. From environment variables

using GenerativeAI.Web;

builder.Services.AddGenerativeAI();

With no explicit options, values come from environment variables:

Option Environment variable Default
Credentials.ApiKey GOOGLE_API_KEY empty
ProjectId GOOGLE_PROJECT_ID none
Region GOOGLE_REGION us-central1
Model GOOGLE_AI_MODEL GoogleAIModels.DefaultGeminiModel
IsVertex none true if GOOGLE_PROJECT_ID is set, otherwise false
ExpressMode none false

2. With a GenerativeAIOptions object

using GenerativeAI;
using GenerativeAI.Web;

builder.Services.AddGenerativeAI(new GenerativeAIOptions
{
    Model = GoogleAIModels.Gemini38Flash,
    Credentials = new GoogleAICredentials
    {
        ApiKey = Environment.GetEnvironmentVariable("GOOGLE_API_KEY")
                 ?? throw new InvalidOperationException("GOOGLE_API_KEY is not set")
    }
});

For Vertex AI, set IsVertex = true with ProjectId and Region and configure authentication (see below):

builder.Services.AddGenerativeAI(new GenerativeAIOptions
{
    IsVertex = true,
    ProjectId = "your-project-id",
    Region = "us-central1",
    Model = VertexAIModels.Gemini.Gemini38Flash
}).WithAdc();

v4 behaviour: IsVertex inference. When you pass a GenerativeAIOptions object without setting IsVertex, and it has an API key but no ProjectId (and ExpressMode is not true), IsVertex is set to false. The service then uses the Gemini API even if GOOGLE_PROJECT_ID happens to be set in the environment. Otherwise an unset IsVertex falls back to the environment-based default above. Set IsVertex explicitly if you need a specific platform.

3. From an IConfiguration section

builder.Services.AddGenerativeAI(builder.Configuration.GetSection("GenerativeAI"));

Or by section path (binds with BindConfiguration and validates on start):

builder.Services.AddGenerativeAI("GenerativeAI");

appsettings.json

{
  "GenerativeAI": {
    "Model": "models/gemini-3.8-flash",
    "Credentials": {
      "ApiKey": "YOUR_API_KEY"
    }
  }
}

Vertex AI:

{
  "GenerativeAI": {
    "IsVertex": true,
    "ProjectId": "your-project-id",
    "Region": "us-central1",
    "Model": "gemini-3.8-flash",
    "ExpressMode": false
  }
}

With a configuration section, an unset IsVertex uses the environment-based default (true only when GOOGLE_PROJECT_ID is set).

4. With an action

builder.Services.AddGenerativeAI(options =>
{
    options.Model = GoogleAIModels.Gemini38Flash;
    options.Credentials = new GoogleAICredentials(Environment.GetEnvironmentVariable("GOOGLE_API_KEY")!);
});

services.ConfigureGenerativeAI(options => { ... }) adjusts the options after registration.

GenerativeAIOptions

public class GenerativeAIOptions : IGenerativeAIOptions
{
    public string? ProjectId { get; set; }
    public string? Region { get; set; }
    public IGoogleAuthenticator? Authenticator { get; set; }
    public GoogleAICredentials? Credentials { get; set; }
    public bool? IsVertex { get; set; }
    public string? Model { get; set; }
    public bool? ExpressMode { get; set; }
    public string? ApiVersion { get; set; }
}

The Gemini API path requires Credentials.ApiKey; without it the service throws InvalidOperationException("API Key is required for Google AI configuration.") when it is created.

Authentication

Extension methods set GenerativeAIOptions.Authenticator (authenticators come from Google_GenerativeAI.Auth):

Method Authenticator
WithAdc() GoogleCloudAdcAuthenticator (Application Default Credentials)
WithServiceAccount(string jsonFilePath) GoogleServiceAccountAuthenticator from a JSON key file
WithServiceAccount(string serviceAccountEmail, string certificateFilePath, string passPhrase) GoogleServiceAccountAuthenticator from a certificate
WithOAuth(string clientSecretFilePath) GoogleOAuthAuthenticator

They return void, so call them last:

builder.Services.AddGenerativeAI(options)
                .WithServiceAccount("path/to/service_account.json");

See Authentication for details.

Using IGenerativeAiService

public interface IGenerativeAiService
{
    IGenerativeAI Platform { get; }
    IGenerativeModel CreateInstance(string modelName = GoogleAIModels.DefaultGeminiModel);
}

CreateInstance uses its modelName argument, not GenerativeAIOptions.Model, so pass the model you want.

Controller

using GenerativeAI;
using GenerativeAI.Web;
using Microsoft.AspNetCore.Mvc;

[ApiController]
[Route("gemini")]
public class GeminiController : ControllerBase
{
    private readonly IGenerativeAiService _generativeAiService;

    public GeminiController(IGenerativeAiService generativeAiService) =>
        _generativeAiService = generativeAiService;

    [HttpGet("generate")]
    public async Task<string> GenerateAsync(string prompt)
    {
        var model = _generativeAiService.CreateInstance(GoogleAIModels.Gemini38Flash);
        var response = await model.GenerateContentAsync(prompt);
        return response.Text;
    }
}

Minimal API

app.MapGet("/generate", async (string prompt, IGenerativeAiService ai) =>
{
    var model = ai.CreateInstance(GoogleAIModels.Gemini38Flash);
    var response = await model.GenerateContentAsync(prompt);
    return response.Text;
});

IGenerativeModel also provides StreamContentAsync(...) for streaming responses (see Streaming). Use Platform to reach the underlying GoogleAi or VertexAI instance.

A complete sample is in samples/WebAppIntegration.

Microsoft.Extensions.AI in web apps

If your app uses IChatClient, register GenerativeAIChatClient directly; see Microsoft.Extensions.AI IChatClient.

Important considerations

  1. Make sure the environment variables or configuration values are set.
  2. Choose an authentication method that fits your hosting environment (API key, ADC, service account or OAuth).
  3. Keep API keys and service-account files out of source control.

API reference

Clone this wiki locally