获取用于 DateTime CultureInfo 转换的 Web 用户位置

Getting a web users location for DateTime CultureInfo conversion

我正在编写一个 MVC 5 互联网应用程序并将此应用程序部署到 Azure。所有 DateTime 值都以 UTC 格式存储。

将这些值显示为网络用户本地时间的最佳方式是什么?我知道如何将 UTC 日期时间转换为本地时间,但不确定向使用 Azure 网站的国际用户显示这些日期时间值的最佳方式。

我做了一些研究,我读到可以做到以下几点:

  1. 获取 HttpRequest.UserLanguages 字符串数组。
  2. 检索它的第一个元素。第一个元素表示用户的默认或首选语言和地区。
  3. 通过调用 CultureInfo.CultureInfo(String, Boolean) 构造函数实例化代表用户首选文化的 CultureInfo 对象。
  4. 使用 CultureInfo 对象转换 UTC 日期时间。

有没有 better/easier 方法来做到这一点?这是否必须在每个 controller/action 结果中完成,或者可以在一个地方完成吗?有没有人编写了一些我可以使用的代码而不是编写我自己的代码?

提前致谢。

将此添加到您的网络配置中:

<configuration>
  <system.web>
    <globalization culture="auto:en-US" uiCulture="en-US" />
  </system.web>
</configuration>

如果您不打算使用本地化资源,那么您可以省略配置的 uiCulture 部分。

This setting automatically switches the ASP.NET request to the browser client’s language if a match can be found. If the browser doesn’t provide a language or the language can’t be matched to one of the .NET installed cultures, the fallback value is used – in this case en-US.

This setting applies the ASP.NET request thread’s CurrentCulture and UICulture. The culture is switched very early in the ASP.NET HttpApplication lifecycle, so you see the selected culture applied and available even in Application_BeginRequest and then throughout the rest of the request cycle.

The full article about this