Alex
Alex

Reputation: 47

C# / MVC Validate model data and call external API based on the results

I have created an WebAPI web app and I would like to validate the data when POST and based on the results to call an external API. The data will be saved in the database as it is, apart from the validation results. Validation will be done only for calling the external API.
I have created the logic for posting to the external API but I'm not quite sure how it will be the optimal way to validate the data.

My model includes 10 classes like the below Class1 with multiple properties and I've created a controller for each of them. The properties can have the true/false values but as strings.

public class Class1
{
    public ICollection<Class1Data> Data { get; set; }
}

public class Class1Data
{
    public int Id { get; set; }
    public string Prop1{ get; set; }
    public string Prop2 { get; set; }
    ..
    public string Prop10 { get; set; }
}

WebAPI contoller for POST:

[ResponseType(typeof(Class1))]
public async Task<IHttpActionResult> PostClass1(Class1 class1)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    db.Class1.Add(class1);
    await db.SaveChangesAsync();

    return CreatedAtRoute("DefaultApi", new { id = Class1.Id }, class1);
}

I've manage somehow to validate one property and POST to external API but not quite sure how I can do that for all my model classes ( I have around 10, 20 props each ).

var notValid = Class1.Data.Where(x => x.Prop1 == "False");

if (notValid != null)
{
    foreach ( var fault in notValid )
    {
        // Call external API using fault.Prop1 / fault.Prop5 / ..
    }    
}

How could I achieve this? I hope that my question makes any sense to you.

Upvotes: 2

Views: 737

Answers (1)

Aram
Aram

Reputation: 5705

The simplest way is to use Data Annotations:

Examples:

[StringLength(100)]
public string AccountKey { get; set; }

[Required]
[StringLength(100)]
public string FirstName { get; set; }

Or if you need custom validations you can define them as Custom Validation Attributes and use them like below:

[Required]
[CountryCode]
[StringLength(3)]
public string CountryCode { get; set; }

In this sample [CountryCode] is a Custom validation which you can implement like this:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)]
public class CountryCodeAttribute : RegularExpressionAttribute
{
    public CountryCodeAttribute() :
        base("^[A-z]{2,3}([-]{1}[A-z]{2,})?([-]?[A-z]{2})?$")
    {
        ErrorMessage = "Invalid country code.";
    }
}

You will need to import this namespace for this kind of validation:

System.ComponentModel.DataAnnotations

Upvotes: 3

Related Questions