2017-05-11 8 views
0

저는 일반적으로 웹 API를 처음 사용하고 POST를 사용하여 새 데이터베이스 항목을 만들 때 웹 API 코어에 문제가 있습니다. ajax 호출은 다음과 같습니다.웹 API 코어 - 클라이언트 측에서 게시 할 수 없습니다.

addSelectedContract = function (contractId, url, callback) { 
     // hard code url to get working 
     url = "http://localhost:17972/api/selectedcontracts"; 
     var contract = JSON.stringify({ contractId: contractId }); 
     $.ajax({ 
      type: "Post", 
      url: url, 
      data: contract, 
      contentType: "application/json" 
     }).done(callback(status)); 
     }; 

내 API 메소드는 다음과 같습니다.

namespace Properties.API.Controllers 
{ 
    [Route("api/selectedcontracts")] 
    public class SelectedContractController : BaseController 
    { 
     private readonly ISirUoW SirUoW; 
     private readonly SirDb Db; 

     public SelectedContractController(SirDb db, ISirUoW repo, Services.IMailService mailService) 
      : base(mailService) 
     { 
      this.Db = db; 
      this.SirUoW = repo; 
     } 

     [HttpPost()] 
     public IActionResult Post([FromBody] SelectedContract contract) 
     { 
      try 
      { 
       this.SirUoW.SelectContract.Add(contract); 
       return Ok(new OperationStatus 
       { 
        Status = true, 
        OperationID = contract.SelectedContractId 
       }); 
      } 
      catch (Exception e) 
      { 
       Console.WriteLine(e); 
       var status = Mapper.Map<OperationStatus>(e); 
       return Ok(status); 
      } 
     } 

내 테스트는이 결과를 제공합니다.

Invoke-RestMethod http://localhost:xxxx/api/selectedcontracts -Method POST -Body (@{contractId="7"} | ConvertTo-Json) -ContentType "application/json" 
[ERROR] Invoke-RestMethod : The remote server returned an error: (500) Internal Server Error. 
[ERROR] At line:1 char:1 
[ERROR] + Invoke-RestMethod http://localhost:xxxx/api/selectedcontracts -Method POST -Bod ... 
[ERROR] + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 
[ERROR]  + CategoryInfo   : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke- 
[ERROR] RestMethod], WebException 
[ERROR]  + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRes 
[ERROR] tMethodCommand 
[ERROR] 

SelectedContract 클래스는 다음과 같이 정의됩니다. 네임 스페이스 SIR.Domain.Poco { 인터페이스 사용; using System; using System.ComponentModel.DataAnnotations;

public class SelectedContract : IAuditCreated 
{ 
    [Key] 
    public int SelectedContractId { get; set; } 

    public int ContractId { get; set; } 

    public DateTime Created { get; set; } 

    [MaxLength(50)] 
    public string CreatedBy { get; set; } 
} 

} 나는 예제 코드 주위를 검색하고 난 내가 뭘 잘못 볼 수 없습니다.

편집 : 동일한 결과를 얻었지만 변경했습니다. SelectedContract 클래스는 다음과 같이 정의됩니다.

namespace SIR.Domain.Poco 
    { 
     using Interfaces; 
     using System; 
     using System.ComponentModel.DataAnnotations; 

     public class SelectedContract : IAuditCreated 
     { 
      [Key] 
      public int SelectedContractId { get; set; } 

      public int ContractId { get; set; } 

      public DateTime Created { get; set; } 

      [MaxLength(50)] 
      public string CreatedBy { get; set; } 
     } 
    } 

그러나 나는 단지 하나 필드, ContractId을 보낸다. 기본 키 또는 감사 필드를 보내지 않습니다. 그래서 DTO 클래스를 만들었습니다.

namespace Properties.API.Models 
    { 
     public class SelectedContractDto 
     { 
      public int ContractId { get; set; } 
     } 
    } 

그리고 API에서 내 Post 메소드의 서명을 변경했습니다.

 [HttpPost()] 
     public IActionResult Post([FromBody] SelectedContractDto contract) 
     { 
      var selectedContract = new SelectedContract { ContractId = Convert.ToInt32(contract.ContractId) }; 
      try 
      { 
       this.SirUoW.SelectContract.Add(selectedContract); 
       return Ok(new OperationStatus 
       { 
        Status = true, 
        OperationID = selectedContract.SelectedContractId 
       }); 
      } 
      catch (Exception e) 
      { 
       Console.WriteLine(e); 
       var status = Mapper.Map<OperationStatus>(e); 
       return Ok(status); 
      } 
     } 

여전히 500 내부 서버 오류가 발생합니다. 내가 피들러의 모양을 가지고뿐만 아니라 내가 온라인이 오류에 대해 아무것도 찾을 수 없습니다

An unhandled exception occurred while processing the request. 
InvalidOperationException: 'Microsoft.AspNetCore.Mvc.MvcOptions.InputFormatter c2 s' must not be empty. At least one 'Microsoft.AspNetCore.Mvc.Formatters.IInputFormatter' is required to bind from the body. 
Microsoft.As fdc pNetCore.Mvc.ModelBinding.Binders.BodyModelBinderProvider.GetBinder(ModelBinderProviderContext context) 

이 오류를 발견했습니다.

답변

0

나는 당신이 부르는 방법이라고 생각하지만 그 후에 try-catch 블록에 표시되지 않은 오류가 있습니까? 디버그 -> Windows -> 예외 설정에서 "공용 언어 런타임 예외"를 선택하고 다시 시도하십시오.

게시 결과.

+0

메서드에 중단 점을 넣었지만 도달하지 못했습니다. – arame3333

+0

SelectedContract 클래스의 구조를 추가하고 질문을 업데이트하십시오. [this] (http://stackoverflow.com/questions/24625303/why-do-we-have-to-specify-frombody-and-fromuri-in-asp-net-web-api) 및 make [FromBody]를 올바르게 사용하고 있는지 확인하십시오. – lolek

+0

[this] (http://stackoverflow.com/questions/41559050/string-value-is-empty-when-using-frombody-in-asp-net-web-api)를 읽고 약간의 아약스 조작을 시도하십시오. JSON.stringify() 메서드없이 계약 객체를 요청하고 사용하십시오. – lolek