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

查看:658
本文介绍了更改ASP.NET Core中DateTime解析的默认格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

    }
}

该框架能够解析日期,但只能以英语格式.当我将 2017年12月4日作为日期参数传递时,我的意思是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/zh-CN/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天全站免登陆