1

I have created a get get by id and a delete api controller that are working just fine. What I am having problems with is creating an edit all the data by id. My examples of my api controllers look as:

[Authorize]
[Route("api/complaints")]
//get all
[HttpGet("")]
    public JsonResult Get()
    {
        var complaints = _repository.GetAll();
        var results = Mapper.Map<IEnumerable<CoViewModel>>(comps);
        return Json(results);
    }
//get by id
[HttpGet("{id}", Name = "GetByIdComp")]
    public IActionResult GetById(int id)
    {
        var complaints = _repository.GetById(id);
        if (complaints == null)
        {
            return HttpNotFound();
        }

        return new ObjectResult(comps);
    }
//delete by id
[HttpDelete("{id}")]
    public void Delete(int id)
    {
        _repository.Remove(id);
        _repository.SaveAll();
    }

//update/edit api not working
[HttpPut("{id}")]
    public JsonResult Post([FromBody] CoViewModel vm, int id)

    {
        try
        {
            if (ModelState.IsValid)
            {
                var obj = Mapper.Map<COMP>(vm);
                //Mapping from VM to Entities
                _logger.LogInformation("made a change");
                COMPLAINT updated = _repository.UpdateComp(obj, id);
                Response.StatusCode = (int)HttpStatusCode.Accepted;
                return Json(Mapper.Map<CoViewModel>(updated)); //Mapping from Ents to VM for the client
            }
        }
        catch (Exception ex)

        {
            _logger.LogError("N'error", ex);
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return Json(new { Message = ex.Message });
        }

        Response.StatusCode = (int)HttpStatusCode.BadRequest;
        return Json(new { Message = "Failed", ModelState = ModelState });
    }

My repository for my api controller is this:

        public COMP UpdateComp(COMP newObj, int idOriginal)

    {

        var original = _context.Comps.FirstOrDefault(m => m.ID == idOriginal);
//Other related tables to update
        //original.CHECKLISTs = newObj.CHECKLISTs;
        //original.Division = newObj.Division;
        _context.SaveChanges();
        return original;
    }

When I try to use postman to change by id and put in the http and seend in a put or post, I get the error:

{message": "Failed",
"modelState": {
"": {
  "rawValue": null,
  "attemptedValue": null,
  "errors": [
    {
      "exception": {
        "ClassName": "Newtonsoft.Json.JsonReaderException",
        "Message": "Unexpected character encountered while parsing number: W. Path '', line 1, position 6.",
        "Data": null,
        "InnerException": null,
        "HelpURL": null,
        "StackTraceString": "   at Newtonsoft.Json.JsonTextReader.ReadNumberIntoBuffer()\r\n   at Newtonsoft.Json.JsonTextReader.ParseNumber()\r\n   at Newtonsoft.Json.JsonTextReader.ParseValue()\r\n   at Newtonsoft.Json.JsonTextReader.ReadInternal()\r\n   at Newtonsoft.Json.JsonTextReader.Read()\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter)\r\n   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)",
        "RemoteStackTraceString": null,
        "RemoteStackIndex": 0,
        "ExceptionMethod": "8\nReadNumberIntoBuffer\nNewtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed\nNewtonsoft.Json.JsonTextReader\nVoid ReadNumberIntoBuffer()",
        "HResult": -2146233088,
        "Source": "Newtonsoft.Json",
        "WatsonBuckets": null
      },
      "errorMessage": ""
    }
  ],
  "validationState": 1
},
"id": {
  "rawValue": "909",
  "attemptedValue": "909",
  "errors": [],
  "validationState": 2
}
}
}

1 Answer 1

1

Is there any chance that you have any HTTP Headers that are being included in your request by default (or any other data besides your object)?

Based on your error message, it looks like your application is attempting to serialize your request but sees an expected character and subsequently blows up. I'd recommend ensuring that you are actually passing your proper data (and just your data) and ensuring that it in the format you expect.

You'll want to ensure that you are send the data through Postman as raw.

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, so close!! I was actually using the body form version then switched to raw in postman! That didn't return an error and said 202 accepted except the return data (return original) still returns the original data and the record remains unchanged. Am I missing something in my code?
It's likely because your actual changes to the element are commented out within your UpdateComp() action. If you pull the original entity, make your changes (to the original object) and then return original the changes that you added should be persisted and returned.
I see what you are saying. I actually don't know how to make changes to the original. I am still trying to understand how the repository makes changes to the COMP and stores it, then when I add the checklists I put the checklists in my json raw code and it says 404 not found. Do you happen to have an example of how to make changes to the original. Obviously the originally is being pulled correctly as it is being returned, right? Thank you in advance!
An example like this one is what I was referring to. This should return your 'updated' version and then you can pass it out using return Json(Mapper.Map<CoViewModel>(updated));
Thank you. I do have that setup. I have uncommented out my checklists and then I passed it out using the return Json(Mapper.Map<CoViewModel>(updated)); and I am still getting the original data.

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.