如何使用ServiceStack Razor呈现本地化的内容页面?

时间:2013-11-28 11:32:07

标签: razor servicestack

我需要为每种文化分别使用default.cshtml。例如,default.en.cshtml,default.dk.cshtml等。应根据当前的请求文化选择正确的内容页面。

使用ServiceStack实现这一目标的最佳方法是什么? IVirtualPathProvider实现?

已解决!适合我:

Plugins.Add(new CultureAwareRazorFormat()) 

已添加到AppHost中。

相关内容:

public class CultureAwareRazorFormat : RazorFormat
{
    public override ServiceStack.Razor.Managers.RazorPageResolver CreatePageResolver()
    {
        return base.CreatePageResolver();
    }

    public override ServiceStack.Razor.Managers.RazorViewManager CreateViewManager()
    {
        return new CultureAwareRazorViewManager(this, VirtualPathProvider);
    }
}


public class CultureAwareRazorViewManager : RazorViewManager
{
    public CultureAwareRazorViewManager(IRazorConfig viewConfig, IVirtualPathProvider virtualPathProvider) : base(viewConfig, virtualPathProvider)
    {

    }

    public override RazorPage GetPage(string absolutePath)
    {
        var extension = VirtualPathUtility.GetExtension(absolutePath);
        if (extension != null)
        {
            string path = absolutePath.Remove(absolutePath.IndexOf(extension, System.StringComparison.Ordinal));
            var localizedPage = TryGetLocalizedPage(path, extension, Thread.CurrentThread.CurrentUICulture);
            if (localizedPage != null) return localizedPage;
        }

        return base.GetPage(absolutePath);
    }

    private RazorPage TryGetLocalizedPage(string path, string extension, CultureInfo culture)
    {
        var result = base.GetPage(path + "." + culture.ToString().ToLower() + extension);
        if (result != null) return result;

        result = base.GetPage(path + "." + culture.TwoLetterISOLanguageName + extension);
        if (result != null) return result;

        result = base.GetPage(path + "." + culture.ThreeLetterISOLanguageName + extension);
        if (result != null) return result;

        return null;
    }

}

0 个答案:

没有答案