ASP.NET Core Web多语言项目

公司效益好了,准备和国外做生意,这个时候就需要多语言了。

> 1. 这是一个ASP.NET Core Web多语言项目,主要展示项目的不同:
> 2. 第一种:www.xxx.com/en/index; www.xxx.com/zh/index; ,这种事通过路由来处理的
> 3. 第二种: www.xxx.com/index/en; www.xxx.com/index/zh ,这种可以用cookie保存,通过cookie来判断
> 4. 第三种:www.en.xxx.com; www.zh.xxx.com,这种方案就是发布两个项目,属于比较简单的,有多少种语言就发布多少种,上面的两种发布的是同一个版本的
> 5. 第一种,第三种一般用于两个项目差别比较大的情况,第二种一般用于项目只有内容不同,其他的都相同的情况

创建项目

新建一个ASP.NET Core Web项目,选择Web应用程序(模型视图控制器)

创建controller

创建一个EnController、ZhController、MoreController

using Microsoft.AspNetCore.Mvc;

namespace MoreLanguage.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}
using Microsoft.AspNetCore.Mvc;

namespace MoreLanguage.Controllers
{
    public class EnController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}
using Microsoft.AspNetCore.Mvc;

namespace MoreLanguage.Controllers
{
    public class ZhController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}
using Microsoft.AspNetCore.Mvc;

namespace MoreLanguage.Controllers
{
    public class MoreController : Controller
    {
        public ActionResult Index(string lang)
        {
            ViewBag.lang = lang == "en" ? "Hello World!" :
                lang == "zh" ? "世界,你好!" : $"你的语言我不懂:{lang}";
            return View();
        }
    }
}

创建对应的视图

@{
    ViewData["Title"] = "Index";
}

<h2>Hello World!</h2>

这里不再重复视图代码

修改Route

//Startup.cs文件
app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "more_route",
        template: "More/{action}/{lang}",
        defaults: new { controller = "More" });

    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});

效果

不同的路由查看效果

https://localhost:44318/

https://localhost:44318/En

 https://localhost:44318/Zh

https://localhost:44318/More/Index/en

https://localhost:44318/More/Index/zh

git地址

https://github.com/jasonhua95/samll-project/tree/master/MoreLanguage

原文地址:https://www.cnblogs.com/zhao123/p/10497044.html