2017-05-11 58 views
0

我是一般的web api,並且在使用POST創建新的數據庫條目時遇到web api核心問題。 ajax調用看起來像;Web 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); 
      } 
     } 

我從powershell的測試給出了這個結果;

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 Interfaces;使用系統的 ; 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; } 
     } 
    } 

並改變了我的Post方法在API中的簽名;

 [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塊嗎?在Debug - > Windows - > Exception Settings中檢查「Common Language Runtime Exceptions」,然後再試一次。

發佈結果。

+0

我在方法中放置了一個斷點,但它沒有達到它。 – arame3333

+0

請添加SelectedContract類的結構並更新您的問題。 也讀[this](http://stackoverflow.com/questions/24625303/why-do-we-have-to-specify-frombody-and-fromuri-in-asp-net-web-api)並使確定你正在使用[FromBody]。 – lolek

+0

閱讀[本](http://stackoverflow.com/questions/41559050/string-value-is-empty-when-using-frombody-in-asp-net-web-api)並嘗試操縱一點點你的阿賈克斯請求和使用你的合同對象沒有JSON.stringify()方法 – lolek