I am trying to add Globalization to an Intranet application, using a cookie to allow users a culture preference. The middleware is set up and running but I have run into an issue with appending to the cookie based on the UI selection.
The method is straight from the Asp.Net Core documentation as below:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<RequestLocalizationOptions>(
options =>
{
var supportedCultures = new List<CultureInfo>
{
new CultureInfo("en-US"),
new CultureInfo("en-GB"),
new CultureInfo("fr-FR"),
new CultureInfo("es-ES")
};
options.DefaultRequestCulture = new RequestCulture(culture: "en-GB", uiCulture: "en-GB");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
});
services.AddLocalization();
services.AddMvc(config =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
})
.AddViewLocalization();
services.AddSession(options => {
options.CookieName = "Intranet";
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(locOptions.Value);
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
[HttpPost]
public IActionResult SetLanguage(string culture, string returnUrl)
{
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1)
});
return LocalRedirect(returnUrl);
}
The issues are:
I have tried:
From the docs where you got that sample, you can see that the code comes from GitHub with lots of sample projects. This particular sample comes from Localization.StarterWeb.
Your two "missing" methods are actually part of ControllerBase
(which is what Controller
inherits from. So if you put this action method into a controller, it will work.
public class HomeController : Controller
{
[HttpPost]
public IActionResult SetLanguage(string culture, string returnUrl)
{
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
);
return LocalRedirect(returnUrl);
}
}