gpt4 book ai didi

c# - 更改 ASP.NET Core 中 DateTime 解析的默认格式

转载 作者:可可西里 更新时间:2023-11-01 03:08:21 25 4
gpt4 key购买 nike

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

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

}
}

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

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

更新我尝试设置 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 并在我的调试器中得到了这个:

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 作为参数传递存在一些文化问题。

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

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

我做了什么:

1) 定义自定义 Binder (使用“out”参数的 c# 7 语法):

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) 为您的 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 使用:

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

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

关于c# - 更改 ASP.NET Core 中 DateTime 解析的默认格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41642800/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com