Misiu
Misiu

Reputation: 4919

WebAPI allow only single date format

Inside my WebAPI I have method that allows user to register to my page.

[AllowAnonymous]
[Route("create")]
[HttpPost]
public async Task<IHttpActionResult> CreateAccount(MyModel newAccount)
{
}

My model has DateTime field that is filled with date when request is made.
Everything works fine when user sends for example 1990-02-07 but for 07.02.1980 I get incorrect value inside my model - date nad month switch values.
I know I can create custom JsonConverter as shown here, but can I do it globally?

Inside Startup.cs I 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 I can do request with invalid date format.

I would like to globally allow single format for date and time.
I would like to allow yyyy-MM-dd (1990-02-07) and yyyy-MM-dd hh:mm:ss (2016-07-28 11:56:00) and return badrequest or invalid request when other format is specified without even processing data.

Upvotes: 0

Views: 803

Answers (1)

Paresh
Paresh

Reputation: 993

You can create your own Json media formatter for date and register it for DateTime type.. Here is the example code for 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 is how you can register it in Startup.cs

config.Formatters.Add(new JsonDateFormatter());

Upvotes: 1

Related Questions