user18154574
user18154574

Reputation: 97

C# How to validate null optional array parameter in REST API?

Imagine that I have an endpoint that accepts optional MyParam string array attribute. How to check it if it's null or empty with most basic way - Data Annotations would be the best.

https://stackoverflow.com/questions/ask?MyParam=

Update: I want to do it on string array not just string, sorry about confusion. Hope this help to justify why above DataAnnotations don't work.

Upvotes: 2

Views: 1121

Answers (1)

beautifulcoder
beautifulcoder

Reputation: 11340

I think what you're looking at here is a custom model validation attribute.

For example:

public class MyParamValidationAttribute : ValidationAttribute
{
    public MyParamAttribute(string param)
    {
        Param = param;
    }

    public string Param { get; }

    public string GetErrorMessage() =>
        $"Invalid param value {param}.";

    protected override ValidationResult IsValid(object value,
        ValidationContext validationContext)
    {
        var myParam = (string)value;

        if (string.IsNullOrEmpty(myParam))
        {
            return new ValidationResult(GetErrorMessage());
        }

        return ValidationResult.Success;
    }
}

https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-3.1#custom-attributes-1

Upvotes: 2

Related Questions