Allow Invalid Date in ASP.NET Core API Service












0














We have a API service that we are updating and we converted some date objects from strings to DateTime objects. In the old code we tested the string if it would parse to a data time or not. If it was a bad formatted string, it would assign DateTime.Min and continue on. Now customers are sending in bad dates and it blows up since the serialization happens outside our code (MVC Controller). I am trying to find some way that when serializing a DateTime object, if it can not parse it, it just returns DateTime.Min instead of blowing up the call.



Here is the response from the API Call.



{
"date": [
"Could not convert string to DateTime: Invalid Date. Path 'date', line 3, position 24."
]
}


===== UPDATE =====



I finally found somewhere that recommended a custom JsonConverter. I finally got something that works, but there is little out there so if there is something I could do better I am all ears.



Custom Converter



  public class DateConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
try
{
return DateTime.Parse(reader.Value.ToString());
}
catch (Exception ex)
{
return DateTime.MinValue;
}
}

public override bool CanConvert(Type objectType)
{
return objectType == typeof(DateTime);
}
}


DTO Class



public class Request
{

[JsonConverter(typeof(SafeDateConverter))]
public DateTime Date { get; set; }
}









share|improve this question
























  • Please provide a Minimal, Complete, and Verifiable example
    – tura08
    Nov 15 '18 at 0:10










  • What code would you like me to include? This error is happening before it even hits any of the code that I write. I send in bad date, it gives error. Examples of those are irrelevant. I need to figure out how to override the default settings to gracefully handle this error and unfortunately I do not know where go... hence why I am reaching out for help. I hate posting on here because everyone criticizes and is down vote happy instead of actually trying to help.
    – Brandon Turpy
    Nov 15 '18 at 0:27










  • "I am trying to find some way that when serializing a DateTime object, if it can not parse it, it just returns DateTime.Min instead of blowing up the call.". What have you tried so far?
    – tura08
    Nov 15 '18 at 0:33












  • Searching online for a solution and everywhere I find says to wrap it in a try catch which I am not able to do as explained in the question. Do I have to prove due diligence to get an answer here? I guess if you do not understand the question I would get it, but if I am asked a question, if I understand the question I answer it.
    – Brandon Turpy
    Nov 15 '18 at 0:37










  • It is hard to help without seeing any code. Can you show what your controller action looks like?
    – tura08
    Nov 15 '18 at 0:43
















0














We have a API service that we are updating and we converted some date objects from strings to DateTime objects. In the old code we tested the string if it would parse to a data time or not. If it was a bad formatted string, it would assign DateTime.Min and continue on. Now customers are sending in bad dates and it blows up since the serialization happens outside our code (MVC Controller). I am trying to find some way that when serializing a DateTime object, if it can not parse it, it just returns DateTime.Min instead of blowing up the call.



Here is the response from the API Call.



{
"date": [
"Could not convert string to DateTime: Invalid Date. Path 'date', line 3, position 24."
]
}


===== UPDATE =====



I finally found somewhere that recommended a custom JsonConverter. I finally got something that works, but there is little out there so if there is something I could do better I am all ears.



Custom Converter



  public class DateConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
try
{
return DateTime.Parse(reader.Value.ToString());
}
catch (Exception ex)
{
return DateTime.MinValue;
}
}

public override bool CanConvert(Type objectType)
{
return objectType == typeof(DateTime);
}
}


DTO Class



public class Request
{

[JsonConverter(typeof(SafeDateConverter))]
public DateTime Date { get; set; }
}









share|improve this question
























  • Please provide a Minimal, Complete, and Verifiable example
    – tura08
    Nov 15 '18 at 0:10










  • What code would you like me to include? This error is happening before it even hits any of the code that I write. I send in bad date, it gives error. Examples of those are irrelevant. I need to figure out how to override the default settings to gracefully handle this error and unfortunately I do not know where go... hence why I am reaching out for help. I hate posting on here because everyone criticizes and is down vote happy instead of actually trying to help.
    – Brandon Turpy
    Nov 15 '18 at 0:27










  • "I am trying to find some way that when serializing a DateTime object, if it can not parse it, it just returns DateTime.Min instead of blowing up the call.". What have you tried so far?
    – tura08
    Nov 15 '18 at 0:33












  • Searching online for a solution and everywhere I find says to wrap it in a try catch which I am not able to do as explained in the question. Do I have to prove due diligence to get an answer here? I guess if you do not understand the question I would get it, but if I am asked a question, if I understand the question I answer it.
    – Brandon Turpy
    Nov 15 '18 at 0:37










  • It is hard to help without seeing any code. Can you show what your controller action looks like?
    – tura08
    Nov 15 '18 at 0:43














0












0








0







We have a API service that we are updating and we converted some date objects from strings to DateTime objects. In the old code we tested the string if it would parse to a data time or not. If it was a bad formatted string, it would assign DateTime.Min and continue on. Now customers are sending in bad dates and it blows up since the serialization happens outside our code (MVC Controller). I am trying to find some way that when serializing a DateTime object, if it can not parse it, it just returns DateTime.Min instead of blowing up the call.



Here is the response from the API Call.



{
"date": [
"Could not convert string to DateTime: Invalid Date. Path 'date', line 3, position 24."
]
}


===== UPDATE =====



I finally found somewhere that recommended a custom JsonConverter. I finally got something that works, but there is little out there so if there is something I could do better I am all ears.



Custom Converter



  public class DateConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
try
{
return DateTime.Parse(reader.Value.ToString());
}
catch (Exception ex)
{
return DateTime.MinValue;
}
}

public override bool CanConvert(Type objectType)
{
return objectType == typeof(DateTime);
}
}


DTO Class



public class Request
{

[JsonConverter(typeof(SafeDateConverter))]
public DateTime Date { get; set; }
}









share|improve this question















We have a API service that we are updating and we converted some date objects from strings to DateTime objects. In the old code we tested the string if it would parse to a data time or not. If it was a bad formatted string, it would assign DateTime.Min and continue on. Now customers are sending in bad dates and it blows up since the serialization happens outside our code (MVC Controller). I am trying to find some way that when serializing a DateTime object, if it can not parse it, it just returns DateTime.Min instead of blowing up the call.



Here is the response from the API Call.



{
"date": [
"Could not convert string to DateTime: Invalid Date. Path 'date', line 3, position 24."
]
}


===== UPDATE =====



I finally found somewhere that recommended a custom JsonConverter. I finally got something that works, but there is little out there so if there is something I could do better I am all ears.



Custom Converter



  public class DateConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
try
{
return DateTime.Parse(reader.Value.ToString());
}
catch (Exception ex)
{
return DateTime.MinValue;
}
}

public override bool CanConvert(Type objectType)
{
return objectType == typeof(DateTime);
}
}


DTO Class



public class Request
{

[JsonConverter(typeof(SafeDateConverter))]
public DateTime Date { get; set; }
}






serialization asp.net-core asp.net-core-mvc






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 15 '18 at 1:22









Tetsuya Yamamoto

14.7k41939




14.7k41939










asked Nov 14 '18 at 23:46









Brandon TurpyBrandon Turpy

393119




393119












  • Please provide a Minimal, Complete, and Verifiable example
    – tura08
    Nov 15 '18 at 0:10










  • What code would you like me to include? This error is happening before it even hits any of the code that I write. I send in bad date, it gives error. Examples of those are irrelevant. I need to figure out how to override the default settings to gracefully handle this error and unfortunately I do not know where go... hence why I am reaching out for help. I hate posting on here because everyone criticizes and is down vote happy instead of actually trying to help.
    – Brandon Turpy
    Nov 15 '18 at 0:27










  • "I am trying to find some way that when serializing a DateTime object, if it can not parse it, it just returns DateTime.Min instead of blowing up the call.". What have you tried so far?
    – tura08
    Nov 15 '18 at 0:33












  • Searching online for a solution and everywhere I find says to wrap it in a try catch which I am not able to do as explained in the question. Do I have to prove due diligence to get an answer here? I guess if you do not understand the question I would get it, but if I am asked a question, if I understand the question I answer it.
    – Brandon Turpy
    Nov 15 '18 at 0:37










  • It is hard to help without seeing any code. Can you show what your controller action looks like?
    – tura08
    Nov 15 '18 at 0:43


















  • Please provide a Minimal, Complete, and Verifiable example
    – tura08
    Nov 15 '18 at 0:10










  • What code would you like me to include? This error is happening before it even hits any of the code that I write. I send in bad date, it gives error. Examples of those are irrelevant. I need to figure out how to override the default settings to gracefully handle this error and unfortunately I do not know where go... hence why I am reaching out for help. I hate posting on here because everyone criticizes and is down vote happy instead of actually trying to help.
    – Brandon Turpy
    Nov 15 '18 at 0:27










  • "I am trying to find some way that when serializing a DateTime object, if it can not parse it, it just returns DateTime.Min instead of blowing up the call.". What have you tried so far?
    – tura08
    Nov 15 '18 at 0:33












  • Searching online for a solution and everywhere I find says to wrap it in a try catch which I am not able to do as explained in the question. Do I have to prove due diligence to get an answer here? I guess if you do not understand the question I would get it, but if I am asked a question, if I understand the question I answer it.
    – Brandon Turpy
    Nov 15 '18 at 0:37










  • It is hard to help without seeing any code. Can you show what your controller action looks like?
    – tura08
    Nov 15 '18 at 0:43
















Please provide a Minimal, Complete, and Verifiable example
– tura08
Nov 15 '18 at 0:10




Please provide a Minimal, Complete, and Verifiable example
– tura08
Nov 15 '18 at 0:10












What code would you like me to include? This error is happening before it even hits any of the code that I write. I send in bad date, it gives error. Examples of those are irrelevant. I need to figure out how to override the default settings to gracefully handle this error and unfortunately I do not know where go... hence why I am reaching out for help. I hate posting on here because everyone criticizes and is down vote happy instead of actually trying to help.
– Brandon Turpy
Nov 15 '18 at 0:27




What code would you like me to include? This error is happening before it even hits any of the code that I write. I send in bad date, it gives error. Examples of those are irrelevant. I need to figure out how to override the default settings to gracefully handle this error and unfortunately I do not know where go... hence why I am reaching out for help. I hate posting on here because everyone criticizes and is down vote happy instead of actually trying to help.
– Brandon Turpy
Nov 15 '18 at 0:27












"I am trying to find some way that when serializing a DateTime object, if it can not parse it, it just returns DateTime.Min instead of blowing up the call.". What have you tried so far?
– tura08
Nov 15 '18 at 0:33






"I am trying to find some way that when serializing a DateTime object, if it can not parse it, it just returns DateTime.Min instead of blowing up the call.". What have you tried so far?
– tura08
Nov 15 '18 at 0:33














Searching online for a solution and everywhere I find says to wrap it in a try catch which I am not able to do as explained in the question. Do I have to prove due diligence to get an answer here? I guess if you do not understand the question I would get it, but if I am asked a question, if I understand the question I answer it.
– Brandon Turpy
Nov 15 '18 at 0:37




Searching online for a solution and everywhere I find says to wrap it in a try catch which I am not able to do as explained in the question. Do I have to prove due diligence to get an answer here? I guess if you do not understand the question I would get it, but if I am asked a question, if I understand the question I answer it.
– Brandon Turpy
Nov 15 '18 at 0:37












It is hard to help without seeing any code. Can you show what your controller action looks like?
– tura08
Nov 15 '18 at 0:43




It is hard to help without seeing any code. Can you show what your controller action looks like?
– tura08
Nov 15 '18 at 0:43












1 Answer
1






active

oldest

votes


















1














Another approach introduce another property on deserialized class of type DateTime? and leave original string property as it is.



public class Request
{
public string Date { get; set; }

private DateTime? _parsedDate;
[JsonIgnore]
public DateTime? ParsedDate
{
get { return _parsedDate; }
set
{
if (DateTime.TryParse(value, out DateTime parsed)
{
_parsedDate = parsed;
return;
}

_parsed = null;
}
}
}


But having custom serializer looks better, because you need change nothing in the code which already uses deserialized object.



Suggestion:

Do not use try ... catch for serializing bad formatted dates, there is DateTime.TryParse method which will do this without throwing exceptions.



And if it is not late, you can use Nullable<DateTime> instead of having DateTime.Min as "not existing" value.






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53310451%2fallow-invalid-date-in-asp-net-core-api-service%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Another approach introduce another property on deserialized class of type DateTime? and leave original string property as it is.



    public class Request
    {
    public string Date { get; set; }

    private DateTime? _parsedDate;
    [JsonIgnore]
    public DateTime? ParsedDate
    {
    get { return _parsedDate; }
    set
    {
    if (DateTime.TryParse(value, out DateTime parsed)
    {
    _parsedDate = parsed;
    return;
    }

    _parsed = null;
    }
    }
    }


    But having custom serializer looks better, because you need change nothing in the code which already uses deserialized object.



    Suggestion:

    Do not use try ... catch for serializing bad formatted dates, there is DateTime.TryParse method which will do this without throwing exceptions.



    And if it is not late, you can use Nullable<DateTime> instead of having DateTime.Min as "not existing" value.






    share|improve this answer




























      1














      Another approach introduce another property on deserialized class of type DateTime? and leave original string property as it is.



      public class Request
      {
      public string Date { get; set; }

      private DateTime? _parsedDate;
      [JsonIgnore]
      public DateTime? ParsedDate
      {
      get { return _parsedDate; }
      set
      {
      if (DateTime.TryParse(value, out DateTime parsed)
      {
      _parsedDate = parsed;
      return;
      }

      _parsed = null;
      }
      }
      }


      But having custom serializer looks better, because you need change nothing in the code which already uses deserialized object.



      Suggestion:

      Do not use try ... catch for serializing bad formatted dates, there is DateTime.TryParse method which will do this without throwing exceptions.



      And if it is not late, you can use Nullable<DateTime> instead of having DateTime.Min as "not existing" value.






      share|improve this answer


























        1












        1








        1






        Another approach introduce another property on deserialized class of type DateTime? and leave original string property as it is.



        public class Request
        {
        public string Date { get; set; }

        private DateTime? _parsedDate;
        [JsonIgnore]
        public DateTime? ParsedDate
        {
        get { return _parsedDate; }
        set
        {
        if (DateTime.TryParse(value, out DateTime parsed)
        {
        _parsedDate = parsed;
        return;
        }

        _parsed = null;
        }
        }
        }


        But having custom serializer looks better, because you need change nothing in the code which already uses deserialized object.



        Suggestion:

        Do not use try ... catch for serializing bad formatted dates, there is DateTime.TryParse method which will do this without throwing exceptions.



        And if it is not late, you can use Nullable<DateTime> instead of having DateTime.Min as "not existing" value.






        share|improve this answer














        Another approach introduce another property on deserialized class of type DateTime? and leave original string property as it is.



        public class Request
        {
        public string Date { get; set; }

        private DateTime? _parsedDate;
        [JsonIgnore]
        public DateTime? ParsedDate
        {
        get { return _parsedDate; }
        set
        {
        if (DateTime.TryParse(value, out DateTime parsed)
        {
        _parsedDate = parsed;
        return;
        }

        _parsed = null;
        }
        }
        }


        But having custom serializer looks better, because you need change nothing in the code which already uses deserialized object.



        Suggestion:

        Do not use try ... catch for serializing bad formatted dates, there is DateTime.TryParse method which will do this without throwing exceptions.



        And if it is not late, you can use Nullable<DateTime> instead of having DateTime.Min as "not existing" value.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 15 '18 at 2:07

























        answered Nov 15 '18 at 1:46









        FabioFabio

        19.3k22044




        19.3k22044






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53310451%2fallow-invalid-date-in-asp-net-core-api-service%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Guess what letter conforming each word

            Port of Spain

            Run scheduled task as local user group (not BUILTIN)