在数据库中,我将值的类型和值存储在字符串中,然后在需要时将其转换回动态对象。尽管在使用法属加拿大路线时转换似乎失败。
下面是使用ASP.NET Core Web应用程序(2.1 MVC)模板快速重新创建错误的步骤:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new[]
{
new CultureInfo("en-CA"),
new CultureInfo("fr-CA")
};
options.DefaultRequestCulture = new RequestCulture("en-CA");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
options.RequestCultureProviders = new List<IRequestCultureProvider>
{
new RouteDataRequestCultureProvider()
};
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
var options = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRouter(routes =>
{
routes.MapMiddlewareRoute("{culture=en-CA}/{*mvcRoute}", subApp =>
{
subApp.UseRequestLocalization(options.Value);
subApp.UseMvc(mvcRoutes =>
{
mvcRoutes.MapRoute(
name: "default",
template: "{culture=en-CA}/{controller=Home}/{action=Index}/{id?}");
});
});
});
}
HomeController.cs
[Route("{culture=en-CA}")]
public class HomeController : Controller
{
[Route("")]
public dynamic Index()
{
return Convert.ChangeType("1,0", Type.GetType("System.Decimal"));
}
}
我在玩耍值字符串时注意到以下内容:
获取/或获取/ en-CA
"1" => "1.0"
"1.0" => "1.0"
"1,0" => "10.0"
获取/ fr-CA
"1" => "1.0"
"1.0" => Error
"1,0" => "1.0"
我不想对数字进行本地化,那么如何只用十进制表示法(1.0)输出所有内容?
答案 0 :(得分:1)
在应用程序数据库边界处与字符串进行双向转换时,请将CultureInfo.InvariantCulture
作为第三个参数传递给Convert.ChangeType
。
例如,从数据库中读取时:
Convert.ChangeType("1.0", Type.GetType("System.Decimal"), CultureInfo.InvariantCulture)
...以及保存到数据库时:
Convert.ChangeType(1.0M, typeof(string), CultureInfo.InvariantCulture)
然后数据库将始终具有相同的格式。