RicoSuter/NSwag

Unhandled OverflowException on decimal property with Range attribute

Open

#1,365 opened on Jun 6, 2018

View on GitHub
 (5 comments) (0 reactions) (0 assignees)C# (6,291 stars) (1,189 forks)batch import
help wantedproject: NJsonSchematype: enhancement

Description

System.ComponentModel.DataAnnotations.RangeAttribute doesn't have constructor for decimal type. One of alternatives is to use constructor which accepts double values for boundaries. JSON schema generator tries to create instance of type using value provided as maximum boundary and fails if double value is greater than decimal.MaxValue with the following exception:

System.OverflowException: Value was either too large or too small for a Decimal.
  in System.Decimal..ctor(Double value)

As far as I can tell it is common practice to use Range attribute with something like double.MaxValue if you only want to have lower limit on your value. Even (double)decimal.MaxValue would fail as the value produced after cast is actually greater than decimal.MaxValue.

The issue is easy to reproduce by creating Web API method with the following response class and trying to generate swagger spec in NSwagStudio:

using System.ComponentModel.DataAnnotations;
public class ResponseDto
{
    [Range(0.0, double.MaxValue)]
    public decimal AnyPositiveDecimal { get; set; }
}

Contributor guide