创建编辑 API 控制器 ASP.NET MVC
Creating an Edit API Controller ASP.NET MVC
我创建了一个 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;
}
当我尝试使用 postman 通过 id 进行更改并将 http 和 seed 放入 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
}
}
}
您是否有任何机会默认包含在您的请求中的任何 HTTP Headers(或除您的 object 之外的任何其他数据)?
根据您的错误消息,您的应用程序似乎正在尝试序列化您的请求,但看到预期的字符并随后崩溃。我建议确保您确实传递了正确的数据(并且只是您的数据)并确保它采用您期望的格式。
您需要确保以 raw
.
的形式通过 Postman 发送数据
我创建了一个 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;
}
当我尝试使用 postman 通过 id 进行更改并将 http 和 seed 放入 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
}
}
}
您是否有任何机会默认包含在您的请求中的任何 HTTP Headers(或除您的 object 之外的任何其他数据)?
根据您的错误消息,您的应用程序似乎正在尝试序列化您的请求,但看到预期的字符并随后崩溃。我建议确保您确实传递了正确的数据(并且只是您的数据)并确保它采用您期望的格式。
您需要确保以 raw
.