当前位置: 首页 > 编程语言 > C#

如何在Asp.NetMVC6中检索AppSettings配置?Share

时间:2023-04-10 22:21:37 C#

如何在Asp.NetMVC6中检索AppSettings配置?假设我使用新的DepencyInjection框架在新的ASP.Net/vNext中配置我的类和依赖项。我该如何使用,如何获得预定义的配置设置?publicvoidConfigureServices(IServiceCollectionservices){//将应用程序设置添加到服务容器。services.Configure(Configuration.GetSubKey("AppSettings"));//将EF服务添加到服务容器。services.AddEntityFramework().AddSqlServer().AddDbContext(options=>options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));//将身份服务添加到服务容器。services.AddIdentity().AddEntityFrameworkStores().AddDefaultTokenProviders();//配置身份验证中间件的选项。//您可以为Google、Twitter和其他中间件添加选项,如下所示。//有关详细信息,请参阅http://go.microsoft.com/fwlink/?LinkID=532715services.Configure(options=>{options.AppId=Configuration["Authentication:Facebook:AppId"];options.AppSecret=Configuration[“身份验证:Facebook:AppSecret”];});services.Configure(options=>{options.ClientId=Configuration["Authentication:MicrosoftAccount:ClientId"];options.ClientSecret=Configuration["Authentication:MicrosoftAccount:ClientSecret"];});//将MVC服务添加到服务容器。服务.AddMvc();services.AddSingleton(a=>{//AppSettingssettingsModel=??//GETCONFIGURATIONSETTINGSFILLED//检索当前设置的技术技巧//varsettingsModel=newAppSettings();//varconfig=Configuration.GetSubKey("AppSettings");//foreach(varitemintypeof(AppSettings).GetProperties().Where(b=>b.CanWrite)){//item.SetValue(settingsModel,config.Get(item.Name));}return新的FooService(settingsModel);});//取消注释以下行以添加WebAPI服务,这样可以更轻松地移植WebAPI2控制器。//您还需要将Microsoft.AspNet.Mvc.WebApiCompatShim包添加到project.json的“依赖项”部分。services.AddWebApiConventions();您可以通过在其结构中输入IOptionsDI服务,在你的FooService中获取AppSettingsIOptions接口是名为OptionsModel的一部分,用于在整个应用程序中访问POCO样式设置(例如:你的AppSettings)。像上面例子中的services.Configure(和services.Configure(options=>services.Configure(options=>这样的调用,其实是注册了DI服务,在解析IOptions请求的时候会调用DI服务对于OptionsManager的DI服务).例:以上是C#学习教程:HowtoretrievetheAppSettingsconfigurationinAsp.NetMVC6?所有内容分享,如果对大家有用,需要详细了解C#学习教程,希望拜托多加关注—publicclassFooService{privatereadonlyAppSettings_settings;publicFooService(IOptionsoptions){_settings=options.Options;}.....}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除,如需转载请注明出处: