Skip to content

Instantly share code, notes, and snippets.

@normj
Created November 9, 2022 17:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save normj/f754f838ade0a102e4d88b28c5bd3ff9 to your computer and use it in GitHub Desktop.
Save normj/f754f838ade0a102e4d88b28c5bd3ff9 to your computer and use it in GitHub Desktop.
Show how to configure the AWS SDK for .NET to be able to make service calls from a Blazor WASM application.
using Amazon;
using Amazon.Runtime;
using Amazon.CognitoIdentity;
using Amazon.Translate;
using BlazorAWSSample;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
// Configure the SDK to not modify user agent header since the browser controls that header.
AWSConfigs.UseAlternateUserAgentHeader = true;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
builder.Services.AddSingleton<AWSCredentials>(provider =>
{
// Use the Cognito Identity credential provider from the AWSSDK.CognitoIdentity package.
// Make sure the Identity Pool has an IAM role for unauthenticated roles with very strict access
// to just the API calls you need.
return new CognitoAWSCredentials("<identity-pool-id>", RegionEndpoint.USWest2);
});
builder.Services.AddSingleton<IAmazonTranslate>(provider =>
{
var awsCredentiats = provider.GetService<AWSCredentials>();
return new AmazonTranslateClient(awsCredentiats, RegionEndpoint.USWest2);
});
var host = builder.Build();
// Configure the AWS SDK to use the HTTP client that can be used from the browser
// instead of the AWS .NET SDK attempting to create its own HTTP clients.
var httpClient = host.Services.GetRequiredService<HttpClient>();
AWSConfigs.HttpClientFactory = new HttpInjectorFactory(httpClient);
await host.RunAsync();
class HttpInjectorFactory : HttpClientFactory
{
private readonly HttpClient InjectedClient;
public HttpInjectorFactory(HttpClient injectedClient)
{
InjectedClient = injectedClient;
}
public override HttpClient CreateHttpClient(IClientConfig clientConfig)
=> InjectedClient;
public override bool DisposeHttpClientsAfterUse(IClientConfig clientConfig)
=> false;
public override bool UseSDKHttpClientCaching(IClientConfig clientConfig)
=> false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment