有谁知道您是否可以控制 ModelState 对象的文化,我在我的多语言应用程序中面临一个问题,其中语言基于您访问该站点的子域,例如:
italia.domain.com - “将文化更改为意大利语”
German.domain.com -“将文化更改为德语”
问题是提交表单时 ModelState 对象上的语言似乎由客户端浏览器控制,而不是当前线程文化。
因此,我正在寻找一个解决方案,我可以修改此行为或覆盖它,以便我的意大利语子域上的语言始终是意大利语,而不是客户端浏览器的语言。
编辑
我已经完成了根据子域更改语言的部分:
var HttpHost = HttpContext.Request.ServerVariables["HTTP_HOST"];
var _hostname = (HttpHost.Split(':').Length > 1) ? HttpHost.Substring(0, HttpHost.IndexOf(':')) : HttpHost;
var allowedHostnames = "italiansubdomain.domain.com|it,frenchsubdomain.domain.com|fr,germansubdomain.domain.com|de,englishsubdomain.domain.com|en".Split(',');
foreach (var hostname in allowedHostnames)
{
if (hostname.StartsWith(_hostname.ToLower()))
{
var lang = hostname.Split('|').Last();
if (lang == "en") lang = "uk";
// Updates the cultures for the dynamic language
var ci = new CultureInfo(lang);
System.Threading.Thread.CurrentThread.CurrentCulture = ci;
System.Threading.Thread.CurrentThread.CurrentUICulture = ci;
}
}
所以我的问题是,当我像这样使用 Modelstate 验证时:
public class Email {
[Required(ErrorMessageResourceName = "validation_required", ErrorMessageResourceType = typeof(Resources.Master)), StringLength(50, MinimumLength = 2, ErrorMessageResourceName = "validation_string_length_2_50", ErrorMessageResourceType = typeof(Resources.Master))]
public string SenderName { get; set; }
[Required(ErrorMessageResourceName = "validation_required", ErrorMessageResourceType = typeof(Resources.Master)), Email(ErrorMessageResourceName = "validation_email_invalid", ErrorMessageResourceType = typeof(Resources.Master))]
public string SenderEmail { get; set; }
[Required(ErrorMessageResourceName = "validation_required", ErrorMessageResourceType = typeof(Resources.Master)), StringLength(50, MinimumLength = 2, ErrorMessageResourceName = "validation_string_length_2_50", ErrorMessageResourceType = typeof(Resources.Master))]
public string ReceiverName { get; set; }
[Required(ErrorMessageResourceName = "validation_required", ErrorMessageResourceType = typeof(Resources.Master)), Email(ErrorMessageResourceName = "validation_email_invalid", ErrorMessageResourceType = typeof(Resources.Master))]
public string ReceiverEmail { get; set; }
public string Comment { get; set; }
}
以及检查模型状态验证部分:
if (!ModelState.IsValid) {
var keys = ModelState.Keys.ToList();
var values = ModelState.Values.ToList();
for (var i = 0; i < keys.Count; i++)
{
var value = values[i];
if (value.Errors.Count > 0)
{
response.AddError(keys[i], value.Errors[0].ErrorMessage);
}
}
}
然后,当我通过 Ajax 响应结果或仅通过调试我根据浏览器语言设置接收错误消息来访问错误时,这就是我想将其更改为当前活动的语言的地方。
编辑
提前致谢, bsthomsen