'string' 不包含 .Net Core 中 'AsInt' 的定义

'string' does not contain a definition for 'AsInt' in .Net Core

我试图在 .Net 核心 MVC 3.1 cshtml 文件中引入以下代码:

<p id="DisableInfo">
    Your session will expire in @(System.Configuration.ConfigurationManager.AppSettings["SessionExpNotice"].AsInt() / 6) minutes, Click Ok to remain logged in or click Cancel to log off.
    If you are logged off any changes will be lost.
</p>

但是在转换为 .NET Core 时,出现此错误

'string' does not contain a definition for 'AsInt' and no accessible extension method 'AsInt' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)

.AsInt() 是 Microsoft.AspNet.WebPages.

的扩展方法

替代方法,通过 Convert.ToInt32().

转换为 int 类型
@(Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SessionExpNotice"]) / 6)

否则你需要为string.AsInt()实现扩展方法。

public static class StringExtensions
{
    public static int AsInt(this string @value)
    {   
        return Int32.TryParse(@value, out int output) 
            ? output 
            : 0;
    }
}

如果您使用的是 .NET Core,请尝试使用:

@using Microsoft.Extensions.Configuration
@inject IConfiguration Configuration
<p id="DisableInfo">
        Your session will expire in @(Convert.ToInt32(Configuration["SessionExpNotice"]) / 6) minutes, Click Ok to remain logged in or click Cancel to log off.
        If you are logged off any changes will be lost.
    </p>

appsettings.json:

{
  ...
  "SessionExpNotice": 6
}