我正在评估asp.net核心和.net核心,我还不确定一些事情。在过去,可以使用开箱即用的web.config配置许多组件。 举一些例子来说明:
有没有办法从配置文件中部分配置这些东西?或者这不再受支持了,我必须自己实现这个配置?在过去,这是一种非常舒适的方式。
答案 0 :(得分:2)
在ASP.NET Core中,Web.config文件仅用于IIS配置,您不能将其用于应用程序配置,但可以使用新的,更好,更灵活的配置选项。
您可以使用多个配置源,但在此示例中我使用的是json。这些示例来自我SimpleAuth项目中的工作代码。
您可以从配置文件中启动配置。
首先,以json格式添加一个映射到您的类的配置文件。您可以看到my example class here,以及它从here
映射的json文件builder.AddJsonFile("simpleauthsettings.json", optional: true);
然后,在ConfigureServices方法中,您将类配置为从配置系统接线,如图所示
services.Configure<SimpleAuthSettings>(Configuration.GetSection("SimpleAuthSettings"));
然后,将类的IOptions访问器添加到Startup.cs中Configure方法的方法签名 Dependency Injection会将它注入到该方法中,以便您可以在那里使用它来配置。具体来说,我是从我的设置对象设置cookie身份验证方案和名称。
值得注意的是,你可以在Configure方法签名中添加你想要的任何东西,只要它是在ConfigureServices方法中注册的东西,DI就能为你注入它。
public class Startup
{
public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
// this file is the custom configuration file to hydrate my settings from
builder.AddJsonFile("simpleauthsettings.json", optional: true);
....
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; set; }
public void ConfigureServices(IServiceCollection services)
{
....
services.Configure<SimpleAuthSettings>(Configuration.GetSection("SimpleAuthSettings"));
....
}
// note that the DI can inject whatever you need into this method signature
// I added IOptions<SimpleAuthSettings> authSettingsAccessor to the method signature
// you can add anything you want as long as you register it in ConfigureServices
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory,
IOptions<SimpleAuthSettings> authSettingsAccessor
)
{
...
// Add cookie-based authentication to the request pipeline
SimpleAuthSettings authSettings = authSettingsAccessor.Value;
var ApplicationCookie = new CookieAuthenticationOptions
{
AuthenticationScheme = authSettings.AuthenticationScheme,
CookieName = authSettings.AuthenticationScheme,
AutomaticAuthenticate = true,
AutomaticChallenge = true,
LoginPath = new PathString("/Login/Index"),
Events = new CookieAuthenticationEvents
{
//OnValidatePrincipal = SecurityStampValidator.ValidatePrincipalAsync
}
};
app.UseCookieAuthentication(ApplicationCookie);
// authentication MUST be added before MVC
app.UseMvc();
}
}