2

I am writing a web api which accepts list of customers in from file upload. Each row in file represents single customers. There can be 'n' customers in a single file.

For each row, validation check is required. The error messages needs to be displayed in respective row.

POST /api/customers List if this is the API, how to perform validations?​

Code is something like this,

public async Task<IHttpActionResult> UploadCustomers(List<Customer> customers)
        {
            if (!ModelState.IsValid)
                return BadRequest();

            //Some action
        }

1 Answer 1

1

You should add a property to your Customer object such as "IsValid," then as you iterate through each row, validate and set the value to true or false.

public class Customer {
   //...
   public bool IsValid { get; set; } = false
}

public async Task<IHttpActionResult> UploadCustomers(List<Customer> customers)
        {
            if (!ModelState.IsValid)
                return BadRequest();

            foreach(var cust in customers)
           {
               if (IsValid(cust))
                { cust.IsValid = true; }
           }

           return customers;
        }

public bool IsValid(Customer cust)
{
  // Validation logic
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for your reply. I am yet to write code for it. Some sample code is edited in post. Since, I am new to web api, finding it difficult to phrase the problem.
I think this statement is not required, if (!ModelState.IsValid) return BadRequest(); as it will validate domain level validationattribute.
I included the code provided in the question, but I agree it may not be required.
How can I extend above code to display errors with respective fields?
That is probably worth asking in a separate question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.