Getting Started with AWS Bedrock in .NET

Getting Started with AWS Bedrock in .NET
Author(s): Ajay Kumar
Last updated: 27 Dec 2025

What is AWS Bedrock and Why Use It from .NET?


If you're a .NET developer looking to integrate generative AI into your applications, AWS Bedrock offers a straightforward way to access foundation models from providers like Anthropic Claude and Amazon Titan. Instead of managing multiple API integrations or dealing with different authentication systems for each provider, Bedrock consolidates access to these models under a single, consistent interface.

With the official AWS SDK for .NET, you can invoke these models using familiar C# code, making it a natural fit for existing .NET projects. This means you can add AI-powered features—like text generation, summarization, or intelligent chat—without leaving your preferred language or toolset.

Why: The Need for Simplicity, Security, and Scale


  • Simplicity: No need to wrangle with REST APIs or manage authentication tokens manually. The AWS SDK for .NET handles all the heavy lifting.
  • Security: Leverage AWS IAM and credentials management for secure access to powerful models.
  • Scale: Bedrock is designed for production workloads, with built-in monitoring, throttling, and cost controls.

Whether you're building a prototype or a production system, integrating GenAI into your .NET stack is now straightforward and robust.

How: Step-by-Step Guide to Using AWS Bedrock from .NET


1. Prerequisites

  • An AWS account with Bedrock access enabled.
  • AWS credentials (Access Key, Secret Key, and Session Token) with permissions for Bedrock.
  • .NET 9 SDK or later installed.
  • The following NuGet packages:
    • AWSSDK.Bedrock
    • AWSSDK.BedrockRuntime
2. Setting Up Your Project

You can use a C# Jupyter notebook (with .NET Interactive) or a simple C# script. Here's how to reference the required libraries:


// ...other using statements...
#r "nuget: AWSSDK.Bedrock, 3.7.0"
#r "nuget: AWSSDK.BedrockRuntime, 3.7.0"

            

3. Authenticating with AWS

⚠️ Authentication and permissions are where most developers struggle. The AWS SDK supports multiple authentication methods, each suited for different scenarios. Choose the one that fits your deployment model.

Method 1: Session Credentials (Local Development)

Use this for quick local testing with temporary credentials (e.g., from AWS STS or temporary session tokens).


SessionAWSCredentials GetCredentials()
{
    // ⚠️ NEVER hardcode credentials in production!
    string accessKey = "<your-access-key>";
    string secretKey = "<your-secret-key>";
    string sessionToken = "<your-session-token>";
    return new SessionAWSCredentials(accessKey, secretKey, sessionToken);
}
                

ℹ️ Security Warning

Session credentials are temporary and should never be hardcoded. Use them only during development with test accounts.

Method 2: IAM User Credentials (Not Recommended for Production)

Use static IAM user credentials for simple scenarios, but this method is less secure for production.


BasicAWSCredentials GetBasicCredentials()
{
    string accessKey = Environment.GetEnvironmentVariable("AWS_ACCESS_KEY_ID");
    string secretKey = Environment.GetEnvironmentVariable("AWS_SECRET_ACCESS_KEY");
    
    if (string.IsNullOrWhiteSpace(accessKey) || string.IsNullOrWhiteSpace(secretKey))
        throw new InvalidOperationException("AWS credentials not found in environment variables.");
    
    return new BasicAWSCredentials(accessKey, secretKey);
}
                

💡 Environment Variables

Store credentials in environment variables, not in appsettings files or source code. Use AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY.

Method 3: EC2 Instance Profile Role (Production on EC2)

This is the recommended approach for production applications running on EC2. The SDK automatically retrieves credentials from the instance metadata without any code changes.


// No credentials needed! The SDK automatically uses the EC2 instance role.
var bedrockClient = new AmazonBedrockClient(RegionEndpoint.USEast1);
var runtimeClient = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1);
                

Method 4: ECS Task Role (Production on ECS/Fargate)

For containerized applications running on ECS or Fargate, use an ECS task execution role.


// No credentials code needed! ECS automatically injects AWS_CONTAINER_CREDENTIALS_RELATIVE_URI
var bedrockClient = new AmazonBedrockClient(RegionEndpoint.USEast1);
                

The IAM permissions are the same as EC2 Instance Profile. Configure the task role in your ECS task definition.

Creating the EC2 Instance Profile Role

To create an EC2 instance profile role with the minimal permissions needed to list models and invoke them:

Step 1: Create an IAM Role

  1. Go to IAM console → Roles → Create Role
  2. Select "AWS service" → "EC2" as the trusted entity
  3. Click "Create Role"

Step 2: Add Inline Policy with Required Permissions

Once the role is created, add this inline policy to grant Bedrock permissions:


{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "bedrock:ListFoundationModels",
        "bedrock:GetFoundationModel"
      ],
      "Resource": "*"
    },
    {
      "Effect": "Allow",
      "Action": [
        "bedrock:InvokeModel",
        "bedrock:InvokeModelWithResponseStream"
      ],
      "Resource": "arn:aws:bedrock:*:*:foundation-model/*"
    }
  ]
}
                

Step 3: Attach the Role to Your EC2 Instance

  1. Go to EC2 console → Instances → Select your instance
  2. Right-click → Security → Modify IAM role
  3. Select the role you created
  4. Click "Update IAM role"

Step 4: Use in Your .NET Code

No code changes needed! The SDK automatically picks up the EC2 instance role:


var bedrockClient = new AmazonBedrockClient(RegionEndpoint.USEast1);
var runtimeClient = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1);
                

Troubleshooting Authentication Issues

If you're getting permission errors, check these common issues:

  • UnauthorizedException or AccessDeniedException: Your credentials don't have Bedrock permissions. Double-check the IAM policy above is attached to your role/user.
  • InvalidUserID or SignatureDoesNotMatch: Your AWS credentials are incorrect or expired. Re-verify your access key and secret key.
  • EC2 instance can't access Bedrock: The instance profile role isn't attached, or the IAM policy is missing. Check the instance details in AWS console.
  • Region issues: Ensure Bedrock is available in your region. Not all AWS regions support Bedrock yet.

Debug tip: Use the AWS CLI to test credentials before using them in your .NET app:


aws bedrock list-foundation-models --region us-east-1
                

Note: The same IAM permissions can also be set up using CloudFormation or AWS CDK if you prefer infrastructure-as-code approaches.

4. Listing Available Foundation Models


async Task ListAvailableModels(AmazonBedrockClient client)
{
    var request = new ListFoundationModelsRequest();
    var response = await client.ListFoundationModelsAsync(request);
    Console.WriteLine($"Found {response.ModelSummaries.Count} models:");
    foreach (var model in response.ModelSummaries.Take(10))
    {
        Console.WriteLine($"  Model ID: {model.ModelId}");
        Console.WriteLine($"  Name: {model.ModelName}");
        Console.WriteLine();
    }
}
            

5. Invoking a Model (Anthropic Claude)


var invokeRequest = new InvokeModelRequest
{
    ModelId = "anthropic.claude-3-sonnet-20240229-v1:0",
    Body = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(
        JsonSerializer.Serialize(new
        {
            anthropic_version = "bedrock-2023-05-31",
            max_tokens = 1024,
            messages = new[] 
            {
                new { role = "user", content = "Tell me about the movie Inception and its impact on cinema." }
            }
        })
    )),
    ContentType = "application/json",
    Accept = "application/json"
};

var runtimeClient = new AmazonBedrockRuntimeClient(GetCredentials());
var invokeResponse = await runtimeClient.InvokeModelAsync(invokeRequest);

using var reader = new System.IO.StreamReader(invokeResponse.Body);
var responseText = await reader.ReadToEndAsync();
            

Example Response from Claude:


Inception was a 2010 science fiction film written and directed by Christopher Nolan. It starred Leonardo DiCaprio, Ellen Page, Tom Hardy, and others.

The movie was very innovative and had a huge impact on cinema for several reasons:

1. Complex Narrative Structure - The film employed a highly complex non-linear narrative structure with multiple nested dream levels. This challenged audiences and pioneered new ways of storytelling on film.

2. Visual Effects - The special effects depicting the bending of cities and gravity-defying fight scenes were groundbreaking and pushed the boundaries of what visual effects could achieve. Many new techniques had to be developed.

3. Original Concept - The premise of corporate espionage taking place within the architecture of the mind was a fresh, original concept that allowed for creativity in visuals and plot.

4. Box Office Success - Despite its cerebral and complex nature, Inception was a huge box office hit, making over $825 million worldwide. This showed audiences had an appetite for intelligent, innovative blockbusters.

5. Influenced Other Films - Its success inspired other thought-provoking, concept-driven science fiction films and showed Hollywood that movies could be both popular and intellectually chewy.

Inception was a landmark for introducing mainstream audiences to Nolan's incredible vision and raised the bar for what could be achieved through film in terms of originality, visual spectacle, and narrative sophistication. It had a major influence on science fiction and blockbuster filmmaking in the 2010s.
            

6. Putting It All Together

Here's a minimal, complete example (see the notebook for the full version):


// ...library references and using statements...

AmazonBedrockClient bedrockClient = new AmazonBedrockClient(GetCredentials());
await ListAvailableModels(bedrockClient);

// Prepare and invoke the model
// ...invokeRequest as above...

var runtimeClient = new AmazonBedrockRuntimeClient(GetCredentials());
var invokeResponse = await runtimeClient.InvokeModelAsync(invokeRequest);
using var reader = new System.IO.StreamReader(invokeResponse.Body);
var responseText = await reader.ReadToEndAsync();

FormatAndPrintResponse(responseText);
            

Summary


  • What: You can now use AWS Bedrock's powerful GenAI models directly from .NET.
  • Why: It's secure, scalable, and easy to integrate into your existing C# workflows.
  • How: With just a few lines of code, you can list models, send prompts, and process responses—all using the official AWS SDK.

This approach lets you build intelligent, generative features into your .NET apps with minimal friction. Whether you're prototyping or going to production, AWS Bedrock and .NET make GenAI accessible and robust.

References & Further Reading


ℹ️ Important Note

For a full working sample, see the notebook linked above. Replace credentials with your own and ensure you have the necessary AWS permissions.

For reference, the code repository being discussed is available at github: https://github.com/ajaysskumar/dev-arena/blob/main/reference/notebooks/aws-bedrock-demo.ipynb

Thanks for reading through. Please share feedback, if any, in comments or on my email ajay.a338@gmail.com

Copyright © 2026 Dev Codex

An unhandled error has occurred. Reload 🗙