创建编辑API控制器ASP.NET MVC

时间:2016-04-04 21:17:51

标签: asp.net json asp.net-web-api asp.net-apicontroller

我创建了一个get get by id和一个正常工作的delete api控制器。我遇到的问题是通过id创建所有数据的编辑。我的api控制器示例如下:

[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 });
    }

我的api控制器的存储库是:

        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;
    }

当我尝试使用邮递员更改ID并输入http并在put或post中发送时,我收到错误:

{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 个答案:

答案 0 :(得分:1)

默认情况下(或您的对象以外的任何其他数据)是否有可能包含在您的请求中的任何HTTP标头?

根据您的错误消息,您的应用程序似乎正在尝试序列化您的请求,但会看到预期的字符并随后爆炸。我建议确保您确实传递了正确的数据(以及您的数据)并确保其格式符合您的预期。

您希望确保通过邮递员将数据作为raw发送。