Doing some actions (setting language) before controller initializes in Web API

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 ?

Upvotes: 3

Views: 1052

Answers (1)

Muthu
Muthu

Reputation: 2685

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.

Upvotes: 2

Related Questions