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

查看:12
本文介绍了更改 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 解析的默认格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆