Indicate required properties of complex input para

2019-07-10 04:51发布

问题:

In this method

/// <summary>
        /// Gets activity logs.
        /// </summary>
        /// <param name="locationId">Location id.</param>
        /// <param name="filter">Activity log filter options.</param>
        /// <response code="200">OK</response>
        [ResponseType(typeof(ActivityLogResponse))]
    public async Task<HttpResponseMessage> FetchActivityLogs(int locationId, ActivityLogFilterOptions filter)
                    {
            }

ActivityLogFilterOptions has some required properties and some are optional. Is there any way to indicate this in Swagger UI API Parameters?

ActivityLogFilterOptions Class:

/// <summary>
    /// Represents an activity log filter options.
    /// </summary>
    public class ActivityLogFilterOptions
    {
        /// <summary>
        /// Gets or sets the device ids to which the activity logs to be fetched.
        /// </summary>
        public string DeviceIds { get; set; }

        /// <summary>
        /// Gets or sets the start date for of the search.
        /// </summary>
        [DateTimeCompare("ToDate",
            ValueComparison.IsLessThan, ErrorMessage = "From date must be earlier than end date.")]
        public DateTime? FromDate { get; set; }

        /// <summary>
        /// Gets or sets the end date for the search.
        /// </summary>
        [DateTimeCompare("FromDate",
            ValueComparison.IsGreaterThan, ErrorMessage = "To date must be later than from date.")]
        public DateTime? ToDate { get; set; }

        /// <summary>
        /// Gets or set the page index.
        /// </summary>
        [Required]
        [Range(0, int.MaxValue)]
        public int? PageIndex { get; set; }

        /// <summary>
        /// Gets or sets the maximum record count per page.
        /// </summary>
        [Required]
        [Range(1, short.MaxValue)]
        public int? RecordsPerPage { get; set; }

        /// <summary>
        /// Gets or sets the activity log groups.
        /// </summary>
        public string Groups { get; set; }
    }

回答1:

Yes, if you decorate the properties of your API model with the RequiredAttribute then the property will not be displayed as "optional" in the Swagger UI:

[Required]
[JsonProperty(PropertyName = "your_property")]
 public string YourProperty {get; set;}

For complex objects you can see the optionality of the properties on the model by clicking on "Model" rather than "Example Value" in the "Data Type" column of the "Parameters" section.