2017-10-20 127 views
2

我正在使用MVC.net並將發佈數據發送到我的Web API 2控制器。我不斷收到500內部服務器錯誤消息。儘管啓用了CORS,但無法使用ajax發佈到其他域

我想發佈到另一個域,如果重要?我有2個visual studio實例正在運行,一個充當客戶端,另一個充當服務器。我已經啓用了CORS。

GET的工作正常,但現在我試圖發佈。

我的「服務器」上的控制器是

[HttpPost] 
[Route("api/cms/")] 
public IHttpActionResult Post([FromBody]int accountId, [FromBody]string content, [FromBody]string paneId, [FromBody]string url) 
{ 
    //content 
} 

「客戶」我使用的JavaScript是

function ajaxStart(type, url, data, successDelegate, failDelegate, errorDelegate) { 
    $.ajax({ 
     type: type.toUpperCase(), 
     url: url, 
     contentType: "application/json;charset=utf-8", 
     data: data, 
     dataType: "json", 
     success: function (response) { 
      successDelegate(response); 
     }, 
     failure: function (e) { 
      failDelegate(e.statusText); 
     }, 
     error: function (e) { 
      errorDelegate(e.statusText); //always hit 
     } 
    }) 
} 

的數據與(我故意用廢話創建字符串只是爲了確保格式化沒有任何問題)

var data = JSON.stringify({ accountId: 1, paneId: "_selectedPaneNumber", url: "_url", content: "content" }); 

而'header'view in谷歌Chrome瀏覽器開發工具顯示:

enter image description here

我不知道我做了什麼錯。

+0

[2的WebAPI POST單字符串參數不工作呢](的可能的複製https://stackoverflow.com/questions/37842231/webapi-2-post-with-single-string-parameter-not-wokring ) – Igor

+0

我已經完全更新了我的帖子,現在它不是一個笨蛋。 – MyDaftQuestions

回答

4

在客戶端的JavaScript顯示正常。這個問題似乎與ApiController的操作和參數綁定有關。

最多允許一個參數從消息體中讀取。所以這是行不通的:

public IHttpActionResult Post([FromBody]int accountId, [FromBody]string content, [FromBody]string paneId, [FromBody]string url) { ... } 

其原因規則是要求身體可能存儲在只能讀一次非緩衝流。

來源:Parameter Binding in ASP.NET Web API : Using [FromBody]

考慮在行動服務器端

public class MyModel { 
    public int accountId { get; set; } 
    public string content { get; set; } 
    public string paneId { get; set; } 
    public string url { get; set; } 
} 

創建模型和更新的動作預期。

[HttpPost] 
[Route("api/cms/")] 
public IHttpActionResult Post([FromBody] MyModel model) { 
    //code removed for brevity 
} 
+0

這太好了。我已經提出了一個新的對象,並且如何實現它的工作,但是當我學習時,我無法弄清楚爲什麼FromBody不起作用。謝謝。當網站允許我時,將標記爲答案。並在24小時內獎勵賞金! – MyDaftQuestions

1

如果您想發送一個字符串作爲體執行以下操作:

  • 添加標題:Content-Type: application/x-www-form-urlencoded
  • 變化在體內的字符串值,因此它帶有前綴=字符:=5
+0

同樣的問題仍在繼續。傳遞的值總是爲空 – MyDaftQuestions

+0

對不起,我完全編輯了這個問題,這已不再相關 – MyDaftQuestions

+0

@MyDaftQuestions - 我明白了。下一次,雖然我會建議在解決更大的問題時開始一個新的問題,而不是多次變形相同的問題。做後者這通常是皺眉,也被稱爲「變色龍」的問題。無論如何,我很高興你有你需要繼續編碼的答案。 – Igor

相關問題