OwinMiddleware doesn't preserve culture change

2020-03-04 04:10发布

问题:

I have an owin culture middle ware running very nice.

It just changes the culture according to the url. This works in 4.5.* perfectly. Now when the runtiome is changed to 4.6.1, the culture isn't preserved anymore and as a result it just doesn't work.

I can reproduce it in a very simple solution which only has this middleware simulating the culture change

public class CultureMiddleware : OwinMiddleware
{
    public CultureMiddleware(OwinMiddleware next)
        : base(next)
    {
    }

    public override async Task Invoke(IOwinContext context)
    {
        var culture = new CultureInfo("es-ES");
        Thread.CurrentThread.CurrentCulture = culture;
        Thread.CurrentThread.CurrentUICulture = culture;

        CultureInfo.CurrentCulture = culture;
        CultureInfo.CurrentUICulture = culture;


        await Next.Invoke(context);
    }
}

I attach the middleware to the pipeline it gets execute but when I'm calling an action the controller doesn't have the culture (like it had in .net 4.5.1)

I already posted here but the support is really slow. One Answer every two weeks and then it seems like they haven't tried what they write :-(

https://connect.microsoft.com/VisualStudio/feedback/details/2455357

回答1:

I got a response from microsoft which works for me.

you can try set the following element in your web.config file. This element has to be child to the <appSettings> element.

<add key="appContext.SetSwitch:Switch.System.Globalization.NoAsyncCurrentCulture" value="true" />


回答2:

I also tried to fix it with OwinMiddleware but failed.

My solution was to create an ActionFilterAttribute and register this at startup:

public partial class Startup : UmbracoDefaultOwinStartup
{
    public override void Configuration(IAppBuilder app)
    {
        GlobalFilters.Filters.Add(new CultureCookieFilter());
        base.Configuration(app);   
    }
}

public class CultureCookieFilter : ActionFilterAttribute
{
    private const string CULTURE_KEY = "X-Culture";

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (filterContext.HttpContext.Request.Cookies[CULTURE_KEY] != null)
        {
            var langCookie = filterContext.HttpContext.Request.Cookies[CULTURE_KEY];
            if (langCookie != null)
            {
                var lang = langCookie.Value;
                Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang);
                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);
            }
        }

        base.OnActionExecuting(filterContext);
    }
}