1. <small id='Z1trg'></small><noframes id='Z1trg'>

      1. <legend id='Z1trg'><style id='Z1trg'><dir id='Z1trg'><q id='Z1trg'></q></dir></style></legend>
          <bdo id='Z1trg'></bdo><ul id='Z1trg'></ul>
        <i id='Z1trg'><tr id='Z1trg'><dt id='Z1trg'><q id='Z1trg'><span id='Z1trg'><b id='Z1trg'><form id='Z1trg'><ins id='Z1trg'></ins><ul id='Z1trg'></ul><sub id='Z1trg'></sub></form><legend id='Z1trg'></legend><bdo id='Z1trg'><pre id='Z1trg'><center id='Z1trg'></center></pre></bdo></b><th id='Z1trg'></th></span></q></dt></tr></i><div id='Z1trg'><tfoot id='Z1trg'></tfoot><dl id='Z1trg'><fieldset id='Z1trg'></fieldset></dl></div>

      2. <tfoot id='Z1trg'></tfoot>

      3. 更改 ASP.NET Core 中 DateTime 解析的默认格式

        Change default format for DateTime parsing in ASP.NET Core(更改 ASP.NET Core 中 DateTime 解析的默认格式)

          <tbody id='3XH8v'></tbody>
          <bdo id='3XH8v'></bdo><ul id='3XH8v'></ul>

              <legend id='3XH8v'><style id='3XH8v'><dir id='3XH8v'><q id='3XH8v'></q></dir></style></legend>
              <i id='3XH8v'><tr id='3XH8v'><dt id='3XH8v'><q id='3XH8v'><span id='3XH8v'><b id='3XH8v'><form id='3XH8v'><ins id='3XH8v'></ins><ul id='3XH8v'></ul><sub id='3XH8v'></sub></form><legend id='3XH8v'></legend><bdo id='3XH8v'><pre id='3XH8v'><center id='3XH8v'></center></pre></bdo></b><th id='3XH8v'></th></span></q></dt></tr></i><div id='3XH8v'><tfoot id='3XH8v'></tfoot><dl id='3XH8v'><fieldset id='3XH8v'></fieldset></dl></div>

                <small id='3XH8v'></small><noframes id='3XH8v'>

              • <tfoot id='3XH8v'></tfoot>
                  本文介绍了更改 ASP.NET Core 中 DateTime 解析的默认格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

                  问题描述

                  我在 ASP.NET Core 控制器中得到一个日期,如下所示:

                  I get a Date in an ASP.NET Core Controller like this:

                  public class MyController:Controller{
                      public IActionResult Test(DateTime date) {
                  
                      }
                  }
                  

                  框架能够解析日期,但只能是英文格式.当我将 04.12.2017 作为日期参数传递时,我的意思是 2017 年 12 月 4 日.这将被解析为英文日期,因此我的日期对象的值是 2017 年 4 月 12 日.我尝试仅添加德语使用 这篇 文章以及 这个,但没有成功.

                  The framework is able to parse the date, but only in English format. When I pass 04.12.2017 as date parameter, I mean the 4th of december 2017. This would get parsed as english date, so my date object gets the value 12th of April 2017. I tried adding german only using this article and also this, but without success.

                  需要做什么才能让 ASP.NET Core 自动以正确的德语格式解析日期?

                  What needs to be done that ASP.NET Core automatically parse dates in the correct German format?

                  更新我试图设置 RequestLocalizationOptions

                  Update I Tried to set the RequestLocalizationOptions

                  services.Configure<RequestLocalizationOptions>(opts =>
                  {
                      var supportedCultures = new[]
                      {
                          new CultureInfo("de-DE"),
                      };
                  
                      opts.DefaultRequestCulture = new RequestCulture("de-DE");
                      // Formatting numbers, dates, etc.
                      opts.SupportedCultures = supportedCultures;
                      // UI strings that we have localized.
                      opts.SupportedUICultures = supportedCultures;
                  });
                  

                  还是不行.我调用 example.com/Test?date=12.04.2017 并在我的调试器中得到了这个:

                  Still not working. I call example.com/Test?date=12.04.2017 and got this in my debugger:

                  public IActionResult Test(DateTime date) {
                      string dateString = date.ToString("d"); // 04.12.2016
                      string currentDateString = DateTime.Now.ToString("d"); // 14.01.2016
                      return Ok();
                  }
                  

                  推荐答案

                  遇到了同样的问题.虽然在请求正文中传递 DateTime 可以正常工作(因为 Json 转换器处理此人员),但在查询字符串中传递 DateTime 作为参数存在一些文化问题.

                  Had the same problem. While passing DateTime in request body works fine (because Json converter handles this staff), passing DateTime in query string as a parameter has some culture issues.

                  我不喜欢更改所有请求文化"的方法,因为这可能会影响其他类型的解析,这是不可取的.

                  I did not like the "change all requests culture" approach, bacause this could have impact on other type's parsing, which is not desirable.

                  所以我的选择是使用 IModelBinder 覆盖默认的 DateTime 模型绑定:https://docs.microsoft.com/en-us/aspnet/core/mvc/advanced/custom-model-binding

                  So my choise was to override the default DateTime model binding using IModelBinder: https://docs.microsoft.com/en-us/aspnet/core/mvc/advanced/custom-model-binding

                  我做了什么:

                  1) 定义自定义绑定器(使用'out'参数的c# 7语法):

                  1) Define custom binder (c# 7 syntax for 'out' parameter is used):

                  public class DateTimeModelBinder : IModelBinder
                  {
                      public Task BindModelAsync(ModelBindingContext bindingContext)
                      {
                          if (bindingContext == null)
                              throw new ArgumentNullException(nameof(bindingContext));
                  
                          // Try to fetch the value of the argument by name
                          var modelName = bindingContext.ModelName;
                          var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);
                          if (valueProviderResult == ValueProviderResult.None)
                              return Task.CompletedTask;
                  
                          bindingContext.ModelState.SetModelValue(modelName, valueProviderResult);
                  
                          var dateStr = valueProviderResult.FirstValue;
                          // Here you define your custom parsing logic, i.e. using "de-DE" culture
                          if (!DateTime.TryParse(dateStr, new CultureInfo("de-DE"), DateTimeStyles.None, out DateTime date))
                          {
                              bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, "DateTime should be in format 'dd.MM.yyyy HH:mm:ss'");
                              return Task.CompletedTask;
                          }
                  
                          bindingContext.Result = ModelBindingResult.Success(date);
                          return Task.CompletedTask;
                      }
                  }
                  

                  2) 为您的活页夹定义提供者:

                  2) Define provider for your binder:

                   public class DateTimeModelBinderProvider : IModelBinderProvider
                  {
                      public IModelBinder GetBinder(ModelBinderProviderContext context)
                      {
                          if (context == null)
                          {
                              throw new ArgumentNullException(nameof(context));
                          }
                  
                          if (context.Metadata.ModelType == typeof(DateTime) || 
                              context.Metadata.ModelType == typeof(DateTime?))
                          {
                              return new DateTimeModelBinder();
                          }
                  
                          return null;
                      }
                  }
                  

                  3) 最后,注册您的提供程序以供 ASP.NET Core 使用:

                  3) And finally, register your provider to be used by ASP.NET Core:

                  services.AddMvc(options =>
                  {
                      options.ModelBinderProviders.Insert(0, new DateTimeModelBinderProvider());
                  });
                  

                  现在您的 DateTime 将按预期进行解析.

                  Now your DateTime will be parsed as expected.

                  这篇关于更改 ASP.NET Core 中 DateTime 解析的默认格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

                  本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

                  相关文档推荐

                  Performance overhead of using attributes in .NET(在 .NET 中使用属性的性能开销)
                  Accessing attribute info from DTE(从 DTE 访问属性信息)
                  c# Hide a property in datagridview with datasource(c#使用数据源隐藏datagridview中的属性)
                  Extract Display name and description Attribute from within a HTML helper(从 HTML 帮助器中提取显示名称和描述属性)
                  C# Attributes and their uses(C# 属性及其用途)
                  C# - Getting all enums value by attribute(C# - 按属性获取所有枚举值)

                  <small id='ckrWi'></small><noframes id='ckrWi'>

                  <i id='ckrWi'><tr id='ckrWi'><dt id='ckrWi'><q id='ckrWi'><span id='ckrWi'><b id='ckrWi'><form id='ckrWi'><ins id='ckrWi'></ins><ul id='ckrWi'></ul><sub id='ckrWi'></sub></form><legend id='ckrWi'></legend><bdo id='ckrWi'><pre id='ckrWi'><center id='ckrWi'></center></pre></bdo></b><th id='ckrWi'></th></span></q></dt></tr></i><div id='ckrWi'><tfoot id='ckrWi'></tfoot><dl id='ckrWi'><fieldset id='ckrWi'></fieldset></dl></div>
                        <bdo id='ckrWi'></bdo><ul id='ckrWi'></ul>
                        <tfoot id='ckrWi'></tfoot>
                          <tbody id='ckrWi'></tbody>

                          • <legend id='ckrWi'><style id='ckrWi'><dir id='ckrWi'><q id='ckrWi'></q></dir></style></legend>