search
HomeBackend DevelopmentC#.Net TutorialDetailed introduction to the sample code for multi-language implementation of Asp.Net Core MVC project

This article mainly introduces the Asp.Net Core MVC project implementation multi-language instance (Globalization/Localization), with It has a certain reference value. If you are interested, you can check it out. I just recently implemented a multi-language function for a

Razor

MVC project, called Globalization, Localization, whatever. The final effect to be achieved is to switch the language of the entire site with one click, and only one set of pages needs to be written during development. Let’s get to the point

First, we need to create a CultureConfigurer class to manage localization resources and complete the "translation" link:

Here I used

Static

class, and then execute the Init() method when the MVC project StartUp is actually a bit stupid. Of course, you can also write an interface first and then use dependency injection to create a singleton .

using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Newtonsoft.Json;

namespace Localization
{
  public enum Culture
  {
    Cn,
    En
  }

  public static class CultureConfigurer
  {
    private static Dictionary<string, string> _enDictionary;
    private static Dictionary<string, string> _cnDictionary;

    public static void Init()
    {
      var assembly = Assembly.Load(new AssemblyName("Localization"));

      var resourceNames = assembly.GetManifestResourceNames();
      foreach (var resourceName in resourceNames)
      {
        if (resourceName.EndsWith("en-US.json") || resourceName.EndsWith("zh-CN.json"))
        {
          using (var stream = assembly.GetManifestResourceStream(resourceName))
          {
            if (stream != null)
            {
              using (StreamReader reader = new StreamReader(stream))
              {
                var content = reader.ReadToEnd();
                Dictionary<string, string> localizationDictionary =
                  JsonConvert.DeserializeObject<Dictionary<string, string>>(content);
                if (resourceName.EndsWith("en-US.json"))
                {
                  _enDictionary = localizationDictionary;
                }
                else
                {
                  _cnDictionary = localizationDictionary;
                }
              }
            }
          }
        }
      }
    }

    public static string GetValue(string key, Culture culture)
    {
      switch (culture)
      {
        case (Culture.Cn):
          {
            if (_cnDictionary.ContainsKey(key))
            {
              return _cnDictionary[key];
            }
            else
            {
              return $"[{key}]";
            }
          }
        case (Culture.En):
          {
            if (_enDictionary.ContainsKey(key))
            {
              return _enDictionary[key];
            }
            else
            {
              return $"[{key}]";
            }
          }
        default:
          {
            return $"[{key}]";
          }
      }
    }
  }
}
There are a few points to note here:

1. The enum class Culture is used to represent the language to be implemented. Here I just simply implemented Chinese and English (I don’t understand the others), The corresponding CultureConfigurer class has two Dictionary

in Chinese and English. 2. Use Assembly.Load to load the assembly. The parameter is your own assembly name. I just wrote a

# here. ## 3. I chose the json file for the resource file, also for the convenience of calling in js. Of course, you can also use

xml

or any format you want to use. You only need to adjust the parsing method and load the file content. Just go to the corresponding Dictionary

 4. When you see the GetValue method

, I believe everyone has understood it. In fact, it is multi-language, no matter what language it is, it uses a certain word. key, and then call this method to "translate" into words in the current language. For example, if "Open" is used as the Key, then there should be a KeyValuePair in the Chinese Dictionary that is "Open": "Open", and the corresponding English should have an "Open": "Open", then when Culture is in Chinese, the display will be "Open" means "Open" in English.

 5. Resource files can be created anywhere in the assembly. If your project has a project.json file, then add it in buildOptions. Be careful to modify the path according to your own file location

"embed": {
   "include": [
    "Localization/SourceFiles/*.json"
   ]
  }

If it is VS2017, it is a csproj file, then right-click the resource file to be added, select "

Properties

", change the configuration to "All configurations", and change the "Generate operation" in the advanced configuration properties to " Embedded resources", as shown below:

At this point, we have written the core class to implement localization, and now we need to solve the problem of how to display it on the page:

Create a new class MyRazorPage in the MVC project

using System;
using Microsoft.AspNetCore.Mvc.Razor;
using Localization;

namespace MVC.Views
{
  public abstract class MyRazorPage<TModel> : RazorPage<TModel>
  {
    public virtual string L(string source)
    {
      var value = Context.Request.Cookies["culture"];
      Culture c;
      if (string.IsNullOrEmpty(value) || !Enum.TryParse(value, out c))
      {
        c = Culture.Cn;
      }
      return CultureConfigurer.GetValue(source, c);
    }
  }
}

Note that this class is an

abstract class

,

inheritsRazorPage. Then find the _ViewImports.cshtml file in the Views folder, and add a line "@inherits MVC.Views.MyRazorPage" in it, so that all your RazorPages will inherit the MyRazorPage class, which means you can Write the method you want to use and you can call it directly in cshtml. Here I wrote an L method and called the GetValue method of CultureConfigurer. Then, the text that needs to be translated on the page just needs to be written like @L("Open"). As you can see, I save the user language in Cookie, and everyone can have their own implementation methods here. My implementation method is very simple. When the user switches languages, he accesses an interface, modifies the cookie representing the language, and then refreshes the page.

The above is the detailed content of Detailed introduction to the sample code for multi-language implementation of Asp.Net Core MVC project. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Deploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideDeploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideApr 23, 2025 am 12:06 AM

How to deploy a C# .NET app to Azure or AWS? The answer is to use AzureAppService and AWSElasticBeanstalk. 1. On Azure, automate deployment using AzureAppService and AzurePipelines. 2. On AWS, use Amazon ElasticBeanstalk and AWSLambda to implement deployment and serverless compute.

C# .NET: An Introduction to the Powerful Programming LanguageC# .NET: An Introduction to the Powerful Programming LanguageApr 22, 2025 am 12:04 AM

The combination of C# and .NET provides developers with a powerful programming environment. 1) C# supports polymorphism and asynchronous programming, 2) .NET provides cross-platform capabilities and concurrent processing mechanisms, which makes them widely used in desktop, web and mobile application development.

.NET Framework vs. C#: Decoding the Terminology.NET Framework vs. C#: Decoding the TerminologyApr 21, 2025 am 12:05 AM

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

Demystifying C# .NET: An Overview for BeginnersDemystifying C# .NET: An Overview for BeginnersApr 20, 2025 am 12:11 AM

C# is a modern, object-oriented programming language developed by Microsoft, and .NET is a development framework provided by Microsoft. C# combines the performance of C and the simplicity of Java, and is suitable for building various applications. The .NET framework supports multiple languages, provides garbage collection mechanisms, and simplifies memory management.

C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!