我在我的web API项目中使用net core 3.1。我已经创建了一个API,它接受来自用户的数据。默认情况下,项目中接受MM-dd-yyyy格式。但是我想接受dd-MM-yyyy格式的日期,并相应地验证所有日期。
下面是我的api:
[HttpGet]
public async Task<IActionResult> Get(DateTime fromDate, DateTime toDate)
{
return Ok();
}
此外,我还有一些API,其中日期参数作为JSON在请求体中传递。我尝试了以下答案,但没有任何效果:
https://stackoverflow.com/a/58103218/11742476
当在请求体中传递日期时,上述解决方案起作用,但在URL中传递日期不起作用。
有没有其他方法可以让我做到这一点。?
您可以自定义日期时间格式的模型绑定器,如下所示:
1.DateTimeModelBinderProvider:
public class DateTimeModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (DateTimeModelBinder.SUPPORTED_TYPES.Contains(context.Metadata.ModelType))
{
return new BinderTypeModelBinder(typeof(DateTimeModelBinder));
}
return null;
}
}
2.日期时间建模器:
public class DateTimeModelBinder : IModelBinder
{
public static readonly Type[] SUPPORTED_TYPES = new Type[] { typeof(DateTime), typeof(DateTime?) };
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
if (!SUPPORTED_TYPES.Contains(bindingContext.ModelType))
{
return Task.CompletedTask;
}
var modelName = GetModelName(bindingContext);
var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);
if (valueProviderResult == ValueProviderResult.None)
{
return Task.CompletedTask;
}
bindingContext.ModelState.SetModelValue(modelName, valueProviderResult);
var dateToParse = valueProviderResult.FirstValue;
if (string.IsNullOrEmpty(dateToParse))
{
return Task.CompletedTask;
}
var dateTime = Helper.ParseDateTime(dateToParse);
bindingContext.Result = ModelBindingResult.Success(dateTime);
return Task.CompletedTask;
}
private string GetModelName(ModelBindingContext bindingContext)
{
if (!string.IsNullOrEmpty(bindingContext.BinderModelName))
{
return bindingContext.BinderModelName;
}
return bindingContext.ModelName;
}
}
public class Helper
{
public static DateTime? ParseDateTime(
string dateToParse,
string[] formats = null,
IFormatProvider provider = null,
DateTimeStyles styles = DateTimeStyles.None)
{
var CUSTOM_DATE_FORMATS = new string[]
{
//"MM-dd-yyyy",
"yyyy-MM-dd",
"dd-MM-yyyy"
};
if (formats == null || !formats.Any())
{
formats = CUSTOM_DATE_FORMATS;
}
DateTime validDate;
foreach (var format in formats)
{
if (format.EndsWith("Z"))
{
if (DateTime.TryParseExact(dateToParse, format,
provider,
DateTimeStyles.AssumeUniversal,
out validDate))
{
return validDate;
}
}
if (DateTime.TryParseExact(dateToParse, format,
provider, styles, out validDate))
{
return validDate;
}
}
return null;
}
}
3.启动.cs:
services.AddControllers(option =>
{
// add the custom binder at the top of the collection
option.ModelBinderProviders.Insert(0, new DateTimeModelBinderProvider());
})
如果您仍想显示< code>dd-MM-yyyy格式的日期,请更改您的Startup.cs:
services.AddControllers(option =>
{
option.ModelBinderProviders.Insert(0, new DateTimeModelBinderProvider());
}).AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
});
结果:
参考:
http://www.vickram.me/custom-datetime-model-binding-in-asp-net-core-web-api
更新:
您可以看到,您可以将< code>dd-MM-yyyy日期传递给操作,但是接收格式仍然和以前一样。这是由设计决定的,请参考:
https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-3.1#模型绑定、路由数据和查询字符串的全球化行为
您可以在序列化中添加JsonConverter
public class DateTimeConverter : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return DateTime.Parse(reader.GetString());
}
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm"));
}
}
static readonly JsonSerializerOptions JsonSerOpt = new()
{
Converters =
{
new DateTimeConverter()
}
};