ASP.NET Core + resx - works only default culture - localization

I am trying to port a WebForm app to MVC 6 and am having an issue with getting resources from a resx file. The code in the controller class returns only default resx values.
I tried both setting Thread.CurrentThread.CurrentCulture & Thread.CurrentThread.CurrentUICulture as well as setting Resources.MyResouces.Culture to specific culture, but Resources.MyResouces.Key still returns only the default. What could be the problem?
public IActionResult MyAction(){
Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture =
Resources.test.Culture = CultureInfo.GetCultureInfo("fr-FR");
// The line below still returns the default English resource value
var localizedValue = Resources.test.test_key;
}

WebForms to Asp.Net Core is a pretty huge leap to take. I would recommend starting with the Asp.Net Core localization sample on GitHub to get a clearer picture of how it works.
In particular, you may need to do some more configuration in your Startup.cs file.

Related

Resources in ASP.NET MVC application

I created ASP.NET MVC App and now I want to replace all literals with elements of my resources files.
I created App_GlobalResources folder in root directory and I added two files:
Resources.en-US.resx
Resources.es-ES.resx
My app directories
And in my views, I put this (for example):
<h1>#Resources.MyResource</h1>
But, always i see this error: The name 'Resources' does not exist in the current context.
Error message
What's wrong?
Thanks in advance!
you need to define a single resource with multiple languages
in your case you will have to refer to the resources by name
#Resources.en-US.resx.MyResource
#Resources.en-ES.resx.MyResource
etc.
this is wrong approach
this is a good read
https://ruijarimba.wordpress.com/2011/05/16/asp-net-mvc-localization-generate-resource-files-and-localized-views-using-custom-templates/
and
http://www.codeproject.com/Articles/778040/Beginners-Tutorial-on-Globalization-and-Localizati
I follow the codeproject.com solution http://www.codeproject.com/Articles/778040/Beginners-Tutorial-on-Globalization-and-Localizati)
But when I set the culture (via controller by ajax query) nothing happens:
[HttpPost]
[Authorize]
public JsonResult SetCulture(String cul) {
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cul);
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(cul);
return Json(true, JsonRequestBehavior.AllowGet);
}
cul parameter = "es-US"
Thanks!
I follow this solution http://www.ryadel.com/en/setup-a-multi-language-website-using-asp-net-mvc/#Set-up_a_Multi-Language_Route
I created "Resources" folder in root directory of my solution. And I added Global.resx and Global.en-EN.resx files
But, when I set culture:
Thread.CurrentThread.CurrentCulture = new CultureInfo(cul);
The Strings never changes... :(

MVC3 (Razor) - not changing the UI Culture language on programmatically

I am trying to develop a MVC3 (razor) application with Select language functionality.
Using the following view as a Partial view on _Layout.cshtml
_SelectCulture
<text>
#Html.ActionLink("English", "SetCulture", new { controller = "Culture", culture = "en-GB" })
|
#Html.ActionLink("Welsh", "SetCulture", new { controller = "Culture", culture = "cy-GB" })
</text>
<div>
#System.Threading.Thread.CurrentThread.CurrentUICulture.ToString()
</div>
CultureController
public ActionResult SetCulture(string culture)
{
System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo(culture);
System.Threading.Thread.CurrentThread.CurrentCulture = ci;
System.Threading.Thread.CurrentThread.CurrentUICulture = ci;
return RedirectToAction("Index", "Home");
}
But its Still not changing the Language.
Any help please.
Thanks
Well, you are changing the language of the current thread. The current thread ends with the current request which is a little bit later after your controller action executes. Then you are redirecting to some other controller action. Then ASP.NET spawns a new thread to serve this request which obviously doesn't have the culture set.
So you will have to persist this change somewhere. Basically there are 3 different approaches:
route variable
cookies
session
I am putting them in the order of preference. The first approach consists into integrating a {culture} token in all your routes. IMHO this is the best approach in terms of SEO as well. So you will redirect for example to /fr/home/index if you want to get your site in French. You could then use a custom action filter attribute which will run before each action, inspect the culture route parameter and set the current thread culture (this time for the current action).
Cookies and sessions also involve persisting the current language between the requests. In the first example this is done on the client whereas in the second it is done in the server. Once again a custom action filter could be used to read the value of the language before each action and reflect the current thread culture.
You may take a look at the following guide which uses Session to persist the current language.

Globalization with MVC

I am trying to localize my web page, and have done the following :
Added resource files with some example strings
Added a call to a method to set culture and ui culture on the click event of flag icons :
public void SetCulture(string culture)
{
Thread.CurrentThread.CurrentCulture = new CultureInfo(culture);
Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture);
}
And I have made reference to my resource file strings in my web page :
#Resources.General.String1
I have stepped through my code and the culture is successfully changed in my SetCulture method, but the string does not change on the web page. Can anybody advise why?
I don't understand what you mean with the click event in a ASP.NET MVC application. I would use routing to set the new language. A sample you can find at Localization with ASP.NET MVC using Routing.
Instead of using a Javascript event, you have to reload the whole page.

Is there a way to rename the RequestVerificationToken cookie name?

Using ASP.net MVC v2.0, Any way to change the name of the __RequestVerificationToken cookie? In an effort to conceal our underlying technology stack, I’d like to rename the cookie to something that can’t be traced back to ASP.Net MVC.
More info on this at Steve Sanderson's blog.
ASP.NET MVC 3 and 4 let you change the cookie name by setting the static AntiForgeryConfig.CookieName property.
(Msdn reference here)
I know that the question asks specifically about ASP.NET MVC 2, but this question still returns high up the search engine rankings for appropriate queries such as "ASP.NET MVC AntiForgeryToken cookie name". I thought I'd add the information here to save others from decompiling the ASP.NET MVC 3+ source code like I did.
Looking at the MVC 2 source code I dont think it's possible to change the cookie name. The AntiForgeryData class starts:
private const string AntiForgeryTokenFieldName = "__RequestVerificationToken";
and to get the cookie name it just calls:
string cookieName = AntiForgeryData.GetAntiForgeryTokenName(ViewContext.HttpContext.Request.ApplicationPath);
in the HtmlHelper class. It takes the application path and converts it to base 64 and appends it onto the end of __RequestVerificationToken which is what you see when you view the source.
If you really need to change the name I'd recommend downloading the MVC 2 source code from codeplex and look at creating your own html helper and anti forgery token using the source code as a reference. But in doing this you could always introduce your own bugs...

Test ASP.NET MVC routes using MVC Contrib

I'm trying to set up Route mapping tests using MVC Contrib as described in Test ASP.NET MVC routes using MVC Contrib
The tests compile and execute, but they always fail with the message "The URL did not match any route."
I set up another test to try to get an idea of what the problem is:
Public Sub TestIndexRoute()
Dim routes = New RouteCollection
myMvcApp.MvcApplication.RegisterRoutes(routes)
Assert.That(routes.Count > 0)
Assert.NotNull(routes("Default"), "Default route not found.")
Dim routeData = RouteTestingExtensions.Route("~/Author")
Assert.NotNull(routeData, "routeData is Nothing.")
Assert.That(routeData.Values("controller") = "Author")
End Sub
That test fails on Assert.NotNull(routeData, "routeData is Nothing."), so I know that there must be some problem with the MVCContrib code that is trying to access my app's RouteCollection.
From the blog post:
It also assumes you set your routes in the ASP.NET MVC RouteCollection object.
How do I confirm that I'm doing that? I'm using routes.MapRoute within MvcApplication.RegisterRoutes method in the Global.asax code behind. Is there something else to do to set this up properly?
Edit: I should probably mention that I'm new to unit testing. I've been putting off learning it for too long and this seemed like as good a place to start as any.
Try:
MvcApplication.RegisterRoutes(RouteTable.Routes);
instead of:
Dim routes = New RouteCollection
myMvcApp.MvcApplication.RegisterRoutes(routes)
See RouteTestingExtensions, line 43

Resources