Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 541
now he who must not be named. Avatar asked Feb 02 '26 16:02

now he who must not be named.


1 Answers

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.

like image 103
Muthu Avatar answered Feb 05 '26 04:02

Muthu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!