Skip to content

Instantly share code, notes, and snippets.

@codefrenzy
Created January 9, 2012 15:55
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codefrenzy/1583539 to your computer and use it in GitHub Desktop.
Save codefrenzy/1583539 to your computer and use it in GitHub Desktop.
Localization via an ActionFilterAttribute in ASP.NET MVC 3 web applications
using System.Web.Mvc;
using System.Web.Routing;
using LocalizationSample.Globalization;
namespace LocalizationSample
{
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new LocalizationAttribute());
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"LocalizationIndex",
"{lang}",
new { controller = "Home", action = "Index", lang = "" },
new { lang = @"([^0-9]+)" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
}
}
using System.Web.Mvc;
namespace LocalizationSample.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
}
@using LocalizationSample.Globalization;
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>@LocalizedResourceManager.GetResource("TitleLabel")</h2>
<div>@LocalizedResourceManager.GetResource("DescriptionLabel")</div>
using System.Linq;
using System.Globalization;
using System.Threading;
using System.Web;
using System.Web.Mvc;
namespace LocalizationSample.Globalization
{
public class LocalizationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Resolve and set the current culture
var culture = ResolveCulture(filterContext);
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture = culture;
// Resolve the current site and setup the LocalizedResourceManager
var siteName = ResolveSite();
LocalizedResourceManager.CurrentSiteName = siteName;
// Continue processing the action
base.OnActionExecuting(filterContext);
}
private static CultureInfo ResolveCulture(ControllerContext filterContext)
{
// Priority 1: from a lang parameter in the query string
var culture = CreateCulture(GetLanguageFromRouteData(filterContext));
if (culture != null)
return culture;
// Priority 2: Get culture from user's browser
culture = CreateCulture(GetRequestLanguage(filterContext));
if (culture != null)
return culture;
return Thread.CurrentThread.CurrentCulture;
}
private static string GetLanguageFromRouteData(ControllerContext filterContext)
{
return filterContext.RouteData.Values["lang"] != null ?
filterContext.RouteData.Values["lang"].ToString() : string.Empty;
}
private static string GetRequestLanguage(ControllerContext filterContext)
{
if (filterContext.HttpContext.Request.UserLanguages != null
&& filterContext.HttpContext.Request.UserLanguages.Count() > 0)
{
return filterContext.HttpContext.Request.UserLanguages[0];
}
return string.Empty;
}
private static CultureInfo CreateCulture(string name)
{
try
{
return CultureInfo.CreateSpecificCulture(name);
}
catch
{
return null;
}
}
private static string ResolveSite()
{
var hostUrl = HttpContext.Current.Request.Url.Host;
if (hostUrl.Contains("sitea"))
return "SiteA";
if (hostUrl.Contains("siteb"))
return "SiteB";
if (hostUrl.Contains("sitec"))
return "SiteC";
// Default to "SiteA"
return "SiteA";
}
}
}
using System.Web;
namespace LocalizationSample.Globalization
{
public class LocalizedResourceManager
{
public static string CurrentSiteName { get; set; }
public static string GetResource(string property)
{
try
{
var resourceValue = HttpContext.GetGlobalResourceObject(CurrentSiteName, property);
return resourceValue != null ? resourceValue.ToString() : string.Empty;
}
catch
{
return string.Empty;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment