I am trying to set Language to my controller in Web API (Doing Internationalization Globalization).
I am writing an attribute called SetLanguage and decorate my web-api controller with it
Something like,
[SetLanguage]
public ServiceRequestController : ApiController
But the problem is this:
public class SetAcceptLanguageHeader : Attribute, IControllerConfiguration
{
public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)
{
if (controllerSettings.Request.Headers.AcceptLanguage != null && controllerContext.Request.Headers.AcceptLanguage.Count > 0)
{
var culture = new CultureInfo(controllerContext.Request.Headers.AcceptLanguage.First().Value);
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}
}
}
But, I am not able to do this because I cannot access Request from controllerSettings.
(Though I know the idea of using a BaseController and overriding Initialize method to achieve the same, I am trying to use this [SetLanguage] Attribute`)
Any ideas how ?
You may try using action filters like
public class SetLanguageAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
//Use actionContext.Request to access your request
}
}
This can then be used to decorate the action method with the [SetLanguage] attribute which can possibly set it to the culture as needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With