-1

I'm trying to POST some data via my ASP.NET Web Service API, but it's throwing a DbEntityValidationException when I try and post the JSON string. Where am I going wrong with trying to post my JSON string?

I used this code block to help me debug my issue, but it's telling me that my fields are required when they exist in the JSON string, almost treating the string like it never exists. It let's me know if the request body is null, but regardless of the name value pairs, it still tells me that the fields are required.

The JSON string I'm trying to post is ripped pretty much from the help page

{
  "CUSTOMER_ID": 7.0,
  "CUSTOMER_USERNAME": "sample string 2",
  "CUSTOMER_PASSWORD": "sample string 3",
  "CUSTOMER_NAME": "sample string 4",
  "CUSTOMER_EMAIL": "sample string 5"
}

and the response I receive is

Response: 500

"Message": "An error has occurred.",
"ExceptionMessage": "Validation failed for one or more entities. See 'EntityValidationErrors' property for more details. The validation errors are: CUSTOMER.CUSTOMER_USERNAME: The CUSTOMER_USERNAME field is required.; CUSTOMER.CUSTOMER_PASSWORD: The CUSTOMER_PASSWORD field is required.; CUSTOMER.CUSTOMER_NAME: The CUSTOMER_NAME field is required.; CUSTOMER.CUSTOMER_EMAIL: The CUSTOMER_EMAIL field is required.",
"ExceptionType": "System.Data.Entity.Validation.DbEntityValidationException"
"StackTrace": "   at WebAPI.Models.Entities3.SaveChangesAsync() in C:\\Users\\[username]\\Desktop\\[folder]\\WebAPI\\WebAPI\\WebAPI\\Models\\Model1.Context.cs:line 65\r\n   at WebAPI.Controllers.CUSTOMERsController.<PostCUSTOMER>d__4.MoveNext() in C:\\Users\\[user]\\Desktop\\[folder]\\WebAPI\\WebAPI\\WebAPI\\Controllers\\CUSTOMERsController.cs:line 88\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Threading.Tasks.TaskHelpersExtensions.<CastToObject>d__1`1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()"

The API uses the following method via the controller and model for posting the string.

// POST: api/CUSTOMERs
        [ResponseType(typeof(CUSTOMER))]
        public async Task<IHttpActionResult> PostCUSTOMER(CUSTOMER cUSTOMER)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.CUSTOMERs.Add(cUSTOMER);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (CUSTOMERExists(cUSTOMER.CUSTOMER_ID))
                {
                    return Conflict();
                }
                else
                {
                    throw;
                }
            }

            return CreatedAtRoute("DefaultApi", new { id = cUSTOMER.CUSTOMER_ID }, cUSTOMER);
        }

=============================================================================

namespace WebAPI.Models
{
    using System;
    using System.Collections.Generic;

    public partial class CUSTOMER
    {
        public decimal CUSTOMER_ID { get; set; }
        public string CUSTOMER_USERNAME { get; set; }
        public string CUSTOMER_PASSWORD { get; set; }
        public string CUSTOMER_NAME { get; set; }
        public string CUSTOMER_EMAIL { get; set; }
    }
}

The headers are fine, as I'm using apirequest.io to help me debug, but I'm not entirely sure what's going wrong.

edwardsew
  • 1
  • 2

2 Answers2

0

Try to separate the entity model from controller.

Create a model replica to the entity model, and check like below:

public async Task<IHttpActionResult> PostCUSTOMER(CUSTOMERDTO dto)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (dto != null)
        {
            CUSTOMER cust = new CUSTOMER();
            //write code to assign dto to cust object
            db.CUSTOMERs.Add(cust);
        }

        try
        {
            await db.SaveChangesAsync();
        }
        catch (DbUpdateException)
        {
            if (CUSTOMERExists(dto.CUSTOMER_ID))
            {
                return Conflict();
            }
            else
            {
                throw;
            }
        }

        return CreatedAtRoute("DefaultApi", new { id = dto.CUSTOMER_ID }, dto);
    }




 public class CUSTOMERDTO
{
    public decimal CUSTOMER_ID { `enter code here`get; set; }
    public string CUSTOMER_USERNAME { get; set; }
    public string CUSTOMER_PASSWORD { get; set; }
    public string CUSTOMER_NAME { get; set; }
    public string CUSTOMER_EMAIL { get; set; }
}
0

I inevitably figured it out, requests made from apirequest.io were overwriting with the header application/x-www-form-urlencoded. Switching to Postman worked for me to test API calls.

Always double check with Chrome or Firefox's networking tools.

edwardsew
  • 1
  • 2