c# - WebAPI allow only single date format -


inside webapi have method allows user register page.

[allowanonymous] [route("create")] [httppost] public async task<ihttpactionresult> createaccount(mymodel newaccount) { } 

my model has datetime field filled date when request made.
works fine when user sends example 1990-02-07 07.02.1980 incorrect value inside model - date nad month switch values.
know can create custom jsonconverter shown here, can globally?

inside startup.cs have:

config.maphttpattributeroutes();  config.formatters.remove(config.formatters.xmlformatter); var jsonformatter = config.formatters.oftype<jsonmediatypeformatter>().first(); jsonformatter.serializersettings.contractresolver = new camelcasepropertynamescontractresolver(); jsonformatter.serializersettings.nullvaluehandling = nullvaluehandling.ignore; jsonformatter.serializersettings.dateformatstring = "yyyy-mm-dd"; jsonformatter.serializersettings.dateparsehandling = dateparsehandling.datetime; 

but still can request invalid date format.

i globally allow single format date , time.
allow yyyy-mm-dd (1990-02-07) , yyyy-mm-dd hh:mm:ss (2016-07-28 11:56:00) , return badrequest or invalid request when other format specified without processing data.

you can create own json media formatter date , register datetime type.. here example code media formatter

public class jsondateformatter : jsonmediatypeformatter {     public override system.threading.tasks.task<object> readfromstreamasync(type type, stream readstream, httpcontent content, iformatterlogger formatterlogger, cancellationtoken cancellationtoken)     {         //do date formatting here     }      public override bool canreadtype(type type)     {         if (type == typeof(datetime))             return true;         return false;     } } 

and here how can register in startup.cs

config.formatters.add(new jsondateformatter()); 

Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -