Reputation: 11
I am trying to implement localization in .Netcore but i am stuck in one thing that how will i show the current culture in Url. I have checked and tried many things but i am not able to make it work. I will show what i have implemented.
under my startup ConfigureServices:
services.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
.AddDataAnnotationsLocalization();
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new[]
{
new CultureInfo("de"),
new CultureInfo("en")
};
options.DefaultRequestCulture = new RequestCulture(culture: "de", uiCulture: "de");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
options.RequestCultureProviders = new List<IRequestCultureProvider>
{
new QueryStringRequestCultureProvider(),
new CookieRequestCultureProvider()
};
});
Startup Configure:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(locOptions.Value);
var culture = locOptions.Value.DefaultRequestCulture.Culture;
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseSession();
//configuring mvc routes...
app.UseMvc(routes =>
{
routes.MapRoute(
name: "areaRoute",
template: "{area:exists}/{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" });
routes.MapRoute(
name: "default",
template: "{culture}/{controller}/{action}/{id?}",
defaults: new { culture = culture, controller = "Home", action = "Index" });
});
}
I have created a partial view and changing culture like this culture is changing successfully:-
[HttpPost]
public IActionResult ChangeLanguage(string culture, string returnUrl)
{
Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) }
);
return LocalRedirect(returnUrl);
}
Now I want to show my current culture in url like www.test.com/en/home/view
I have created a route and also setting the culture but it is taking only default culture even after i changed the culture.
Also please tell is this a proper way to implement localization becuase i am too confused on this topic.
Edit:- I just need that my culture in url will be changed when i am changing the culture of my application.
Upvotes: 1
Views: 5360
Reputation: 20106
Remove var culture = locOptions.Value.DefaultRequestCulture.Culture;
in you Configure which always set the culture as default culture.
Below demo is applied to use twoLetterLanguageName.Refer to this tutorial
1.Create a RouteDataRequestCultureProvider
class:
public class RouteDataRequestCultureProvider : RequestCultureProvider
{
public int IndexOfCulture;
public int IndexofUICulture;
public override Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
{
if (httpContext == null)
throw new ArgumentNullException(nameof(httpContext));
string culture = null;
string uiCulture = null;
var twoLetterCultureName = httpContext.Request.Path.Value.Split('/')[IndexOfCulture]?.ToString();
var twoLetterUICultureName = httpContext.Request.Path.Value.Split('/')[IndexofUICulture]?.ToString();
if (twoLetterCultureName == "de")
culture = "de-DE";
else if (twoLetterCultureName == "en")
culture = uiCulture = "en-US";
if (twoLetterUICultureName == "de")
culture = "de-DE";
else if (twoLetterUICultureName == "en")
culture = uiCulture = "en-US";
if (culture == null && uiCulture == null)
return NullProviderCultureResult;
if (culture != null && uiCulture == null)
uiCulture = culture;
if (culture == null && uiCulture != null)
culture = uiCulture;
var providerResultCulture = new ProviderCultureResult(culture, uiCulture);
return Task.FromResult(providerResultCulture);
}
}
2.And a LanguageRouteConstraint
class
public class LanguageRouteConstraint : IRouteConstraint
{
public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
{
if (!values.ContainsKey("culture"))
return false;
var culture = values["culture"].ToString();
return culture == "en" || culture == "de";
}
}
3.startup.cs:
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new List<CultureInfo>
{
new CultureInfo("en"),
new CultureInfo("de"),
};
options.DefaultRequestCulture = new RequestCulture(culture: "en", uiCulture: "en-US");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
options.RequestCultureProviders = new[]{ new RouteDataRequestCultureProvider{
IndexOfCulture=1,
IndexofUICulture=1
}};
});
services.Configure<RouteOptions>(options =>
{
options.ConstraintMap.Add("culture", typeof(LanguageRouteConstraint));
});
services.AddMvc()
.AddRazorPagesOptions(options =>
{
options.Conventions.AddAreaFolderRouteModelConvention("Identity", "/Account/", model =>
{
foreach (var x in model.Selectors)
{
if (x.AttributeRouteModel.Template.StartsWith("Identity"))
{
x.AttributeRouteModel = new AttributeRouteModel()
{
Order = -1,
Template = AttributeRouteModel.CombineTemplates(("{culture=en}"),
x.AttributeRouteModel.Template)
};
}
}
});
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
app.UseMvc(routes =>
{
routes.MapRoute(
name: "MyArea",
template: "{culture:culture}/{area:exists}/{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "LocalizedDefault",
template: "{culture:culture}/{controller}/{action}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{id?}",
defaults: new { controller = "Home", action = "Index" });
});
Then you could change culture in browser url directly using /en/Home/Privacy
.
4.To show culture when you change it,you could modify your redirect url to contains culture in ChangeLanguage
action:
[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) }
);
var array = returnUrl.Split("/");
if (array[1] == "en" || array[1] == "de")//returnUrl like ~/en/Home/privacy
{
array[1] = culture;
return LocalRedirect(String.Join("/", array));
}
else// returnUrl like ~/Home/privacy
{
return LocalRedirect("/" + culture + returnUrl.Substring(1));
}
}
5.set asp-area
for your action in _SelectLanguagePartial.cshtml
, use asp-area=""
if the action is in root area.
<form id="selectLanguage" asp-area="" asp-controller="Home" ...>...
</form>
Upvotes: 3