Reputation: 654
Is there a way to intercept the caller's language in the ASP.NET Core Web API in C#?
I'm referring to the natural language of the caller.
I solved the issue with the following code :
private string GetCulture()
{
var headers = this.Request.Headers;
if (headers.ContainsKey("Accept-Language"))
{
Microsoft.Extensions.Primitives.StringValues token;
headers.TryGetValue("Accept-Language",out token);
return token[0].ToString().Split(';')[0].Split(',')[0];
}
return ("en-GB");
}
Thanks to all.
Upvotes: 0
Views: 391
Reputation: 2042
By language if u mean natural languages (like English) the client can specify this in an http header content-language:en-us
If you’re referring to the programming language, there’s no standard header defined in the http spec to do this.
Some clients include a user-agent
header to tell you what kind of an app made the request. But not all clients do this.
If you have control over your callers, u can set your own http header when the callers make the request to denote the language.
For e.g X-Caller-Language:cs
And interpret this header on your web Api as “the client app is c#”
And if you really want to enforce your callers to specify this header, you should check this header in your code and if it doesn’t exist, you should return an error code 400 with instructions on what you expect.
In any case this shouldn’t be of concern to the server. Your apis should be designed to be platform independent.
Upvotes: 2