Change default format for DateTime parsing in ASP.NET Core

前端 未结 10 1153
情话喂你
情话喂你 2021-02-02 08:57

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

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

    }
}
10条回答
  •  青春惊慌失措
    2021-02-02 09:53

    MVC has always used InvariantCulture for route data and query strings (parameters that go in the URL). The reason behind it is that URLs in localized application must be universal. Otherwise, one url can provide different data depending on the user locale.

    You can replace the query and route ValueProviderFactories with your own that respect current culture (or use method="POST" in forms)

    public class CustomValueProviderFactory : IValueProviderFactory
    {
        public Task CreateValueProviderAsync(ValueProviderFactoryContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }
    
            var query = context.ActionContext.HttpContext.Request.Query;
            if (query != null && query.Count > 0)
            {
                var valueProvider = new QueryStringValueProvider(
                    BindingSource.Query,
                    query,
                    CultureInfo.CurrentCulture);
    
                context.ValueProviders.Add(valueProvider);
            }
    
            return Task.CompletedTask;
        }
    }
    
    services.AddMvc(opts => {
        // 2 - Index QueryStringValueProviderFactory
        opts.ValueProviderFactories[2] = new CustomValueProviderFactory(); 
    })
    

    P.S. It is reasonable behavior, but I don't understand why documentation don't cover this very important thing.

提交回复
热议问题