在 ASP.net 核心应用的强类型配置 class 中使用 System.Uri
Use System.Uri in strongly typed configuration class for ASP.net core app
在我们的 AspNetCore 2.2
应用程序中,我们使用强类型 classes 作为配置部分,
遵循模式:
public static IServiceCollection AddMyConfigSettings(this IServiceCollection services, IConfiguration configuration)
{
MyConfigSettings myConfigSettings = new MyConfigSettings();
configuration.Bind("MyConfig", myConfigSettings);
services.AddSingleton(myConfigSettings);
return services;
}
现在 MyConfigSettings
class 看起来像这样:
public class MyConfigSettings
{
#pragma warning disable CA1056 // Uri properties should not be strings
public string HostUrl { get; set; }
}
有没有一种简单的方法可以使用 System.Uri
而不是 System.String
作为 HostUrl 的类型,这样我们就不需要抑制 Roslyn 分析器警告 CA1056?
将 属性 从 string
更改为 Uri
。
public class MyConfigSettings {
public Uri HostUrl { get; set; }
}
bind 应该会处理剩下的事情。
您也可以像这样绑定到对象图
public static IServiceCollection AddMyConfigSettings(this IServiceCollection services, IConfiguration configuration) {
MyConfigSettings myConfigSettings = configuration.GetSection("MyConfig").Get<MyConfigSettings>();
services.AddSingleton(myConfigSettings);
return services;
}
ConfigurationBinder.Get<T>
binds and returns the specified type. Get<T>
is more convenient than using Bind
.
前面的代码显示了如何在您的示例中使用 Get<T>
,它允许绑定实例直接分配给 属性。
在我们的 AspNetCore 2.2
应用程序中,我们使用强类型 classes 作为配置部分,
遵循模式:
public static IServiceCollection AddMyConfigSettings(this IServiceCollection services, IConfiguration configuration)
{
MyConfigSettings myConfigSettings = new MyConfigSettings();
configuration.Bind("MyConfig", myConfigSettings);
services.AddSingleton(myConfigSettings);
return services;
}
现在 MyConfigSettings
class 看起来像这样:
public class MyConfigSettings
{
#pragma warning disable CA1056 // Uri properties should not be strings
public string HostUrl { get; set; }
}
有没有一种简单的方法可以使用 System.Uri
而不是 System.String
作为 HostUrl 的类型,这样我们就不需要抑制 Roslyn 分析器警告 CA1056?
将 属性 从 string
更改为 Uri
。
public class MyConfigSettings {
public Uri HostUrl { get; set; }
}
bind 应该会处理剩下的事情。
您也可以像这样绑定到对象图
public static IServiceCollection AddMyConfigSettings(this IServiceCollection services, IConfiguration configuration) {
MyConfigSettings myConfigSettings = configuration.GetSection("MyConfig").Get<MyConfigSettings>();
services.AddSingleton(myConfigSettings);
return services;
}
ConfigurationBinder.Get<T>
binds and returns the specified type.Get<T>
is more convenient than usingBind
.
前面的代码显示了如何在您的示例中使用 Get<T>
,它允许绑定实例直接分配给 属性。