What is the best practice in order to send my current culture from Grpc Client to Grpc Server in a c# project using dotnetcore3?
What is the best practice in order to send my current culture from Grpc Client to Grpc Server in a c# project using dotnetcore3?
I managed to do it by adding the culture to the headers and with an Interceptor:
public class ThreadCultureInterceptor : Interceptor
{
public override async Task<TResponse> UnaryServerHandler<TRequest, TResponse>(
TRequest request,
ServerCallContext context,
UnaryServerMethod<TRequest, TResponse> continuation)
{
var headerLanguage = context.RequestHeaders.FirstOrDefault(t => t.Key == "language");
if (headerLanguage != null)
{
Thread.CurrentThread.CurrentCulture = new CultureInfo(headerLanguage.Value);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(headerLanguage.Value);
}
return await continuation(request, context);
}
}
In your Startup.cs:
services.AddGrpc(options =>
{
options.Interceptors.Add<ThreadCultureInterceptor>();
});
On your client application:
var credentials = CallCredentials.FromInterceptor((context, metadata) =>
{
if (!string.IsNullOrEmpty(loginResponse.Token))
{
metadata.Add("Authorization", $"Bearer {loginResponse.Token}");
metadata.Add("Language", "en-US");
}
return Task.CompletedTask;
});
channel = GrpcChannel.ForAddress("https://localhost:5001", new GrpcChannelOptions
{
Credentials = ChannelCredentials.Create(new SslCredentials(), credentials)
});
client = channel.CreateGrpcService<IService>();
Read about CultureInfo. This class holds a string property called Name. Commonly you just need to access the current context by doing CultureInfo.CurrentCulture.
You can also define your own culture in the server and client by setting a value on CultureInfo.CurrentCulture.
Ex:
CultureInfo.CurrentCulture = new CultureInfo("en-US");