ASP.NET Core Web API - DateTime Data Annotations Problem

Cenk 956 Reputation points
2022-12-29T17:25:13.087+00:00

Hello,

I am trying to validate an API action method that has a start date and an end date.

public class OrderHistoryRequestDto  
    {  
        [Required(ErrorMessage = "Please add StartDate to the request.")]  
        [DataType(DataType.Date)]  
        public DateTime StartDate { get; set; }  
        [Required(ErrorMessage = "Please add EndDate to the request.")]  
        [DataType(DataType.Date)]  
        public DateTime EndDate { get; set; }  
    }  

I am supposed to get a 400-bad request if I don't send one of the required fields.

274840-ekran-goruntusu-2022-12-29-201712.png

But instead, it set the missing date as a default value.

274903-ekran-goruntusu-2022-12-29-201634.png

How can I validate this model?

Thank you in advance.

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
698 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,212 questions
{count} votes

Accepted answer
  1. AgaveJoe 26,146 Reputation points
    2022-12-30T13:15:41.523+00:00

    I'm sure Viorel-1 made a typo and is recommending a nullable type.

        public class OrderHistoryRequestDto  
        {  
            [Required(ErrorMessage = "Please add StartDate to the request.")]  
            [DataType(DataType.Date)]  
            public DateTime? StartDate { get; set; }  
            [Required(ErrorMessage = "Please add EndDate to the request.")]  
            [DataType(DataType.Date)]  
            public DateTime? EndDate { get; set; }  
        }  
    

    I tested the model with PostMan and an HTTP GET and received the following validation response.

    {  
        "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",  
        "title": "One or more validation errors occurred.",  
        "status": 400,  
        "traceId": "00-13effc30183cfe634ea13672b70e6373-affffa0f4b34e5f1-00",  
        "errors": {  
            "EndDate": [  
                "Please add EndDate to the request."  
            ]  
        }  
    }  
    
    0 comments No comments

0 additional answers

Sort by: Most helpful