OwinMiddleware doesn't preserve culture change in .net 4.6.*

左心房为你撑大大i 提交于 2019-11-30 17:48:12

问题


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);
    }
}


来源:https://stackoverflow.com/questions/36455801/owinmiddleware-doesnt-preserve-culture-change-in-net-4-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!