把旧系统迁移到.Net Core 2.0 日记(5) Razor/HtmlHelper/资源文件

。_饼干妹妹 提交于 2021-02-12 00:37:06

net core 的layout.cshtml文件有变化, 区分开发环境和非开发环境. 开发环境用的是非压缩的js和css, 正式环境用压缩的js和css

<environment include="Development">
        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css" />
        <link rel="stylesheet" href="~/css/site.css" />
    </environment>
    <environment exclude="Development">
        <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"
              asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
              asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute" />
        <link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true" />
    </environment>

 对view命名空间的引用,现在则改成了使用_ViewImport.cshtml文件,并且用razor语法来配置。

@using FoxCRMCore
@using FoxCRMCore.Models
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

旧项目是把多语言放在资源文件里的. 但找了网上也没有详细讲Globalization的, 微软这篇文章讲的是Localization, 不好用.

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/localization

所以我还是用扩展HtmlHelper的方法, 却出现一个错误: 'IHtmlHelper<dynamic>' does not contain a definition for 'Lang' and the best extension method overload 'LocalizationHelper.Lang(HtmlHelper, string)' requires a receiver of type 'HtmlHelper'

找了好久才发现原因, https://stackoverflow.com/questions/30327764/how-to-create-an-extension-method-on-ihtmlhelperdynamic

现在Razor里的html扩展方法改成IHtmlHelper接口了.

using System;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;

namespace FoxCRMCore
{
    public static class LocalizationHelper
    {
        public static string Lang(this IHtmlHelper html, string key)
        {
            return Resources.Re.ResourceManager.GetString(key);
        }

    }
}

而在界面切换语言,只要在url上传一个culture的参数即可. 在Startup.cs里

app.Use((context, next) =>
            {
                var StrCulture = "en-US";

                if (!string.IsNullOrWhiteSpace(context.Request.Query["culture"]))
                {
                    StrCulture = context.Request.Query["culture"];
                    context.Response.Cookies.Append("foxcrmCoreLang",StrCulture);
                }
                else
                {
                    if (context.Request.Cookies["foxcrmCoreLang"] != null)
                        StrCulture = context.Request.Cookies["foxcrmCoreLang"];
                }

                var culture = new CultureInfo(StrCulture);

                CultureInfo.CurrentCulture = culture;
                CultureInfo.CurrentUICulture = culture;
                // Call the next delegate/middleware in the pipeline
                return next();
            });

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!