{ "ConnectionStrings": { "DefaultConnectionString": "Data Source=..." },"Logging": { "IncludeScopes": false,"LogLevel": { "Default": "Warning" } },"CustomSettings": { "Culture": "es-CO" } }
我无法在以下控制器中加载Culture键:
public AccountController( UserManager<ApplicationUser> userManager,SignInManager<ApplicationUser> signInManager,IEmailSender emailSender,ILogger<AccountController> logger,IConfiguration configuration) { Response.Cookies.Append( CookieRequestCultureProvider.DefaultCookieName,CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(configuration.GetSection("CustomSettings")["Culture"])),new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) } ); }
无论我是否遵循,总是返回NULL:
configuration.GetSection( “CustomSettings”)[ “文化”];
configuration.GetSection( “CustomSettings”)的GetValue( “文化”).
我尝试了基于ASP.NET Core: Step by Step Guide to Access appsettings.json in web project and class library的帮助,并且我创建了具有字符串Culture属性的CustomSettings类,并在Startup中注入如下:
// Load Custom Configuration from AppSettings.json services.Configure<Models.CustomSettings>(Configuration.GetSection("CustomSettings"));
通过注入IOptions来访问customSettings,其值为
customSettings.Value.Culture返回NULL.
第一个问题:¿我做错了什么或缺少什么?
第二个问题:¿为什么在HomeController的索引中执行以下操作会引发异常?
public class HomeController : Controller { public IActionResult Index(IConfiguration configuration) { } }
例外:
处理请求时发生未处理的异常.
InvalidOperationException:无法创建类型为’Microsoft.Extensions.Options.IOptions`1 [[OmniMerchant.Models.CustomSettings,OmniMerchant,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null]]’的实例.模型绑定的复杂类型不能是抽象或值类型,并且必须具有无参数构造函数.
Microsoft.AspNetCore.Mvc.ModelBinding.Binders.ComplexTypeModelBinder.CreateModel(ModelBindingContext bindingContext)
第三个问题:我需要根据appSettings.json上的Culture属性为后台的所有应用程序设置Culture,我读了MSDN documentation,但是我无法实现这一点,¿我怎样才能实现这个目标?
谢谢
解决方法
public class CustomSettings { public string Culture { get; set; } }
然后在Startup.cs中的ConfigureServices方法中注册它
services.Configure<CustomSettings>(Configuration.GetSection("CustomSettings"));
然后使用需要的IOptions注入它
AccountController(IOptions<CustomSettings> settings) { _settings = settings.Value; }