2014-01-24 48 views
0

我想使用Ajax發佈一些數據,但使用內容類型的應用程序/ json時(HTTP/1.1 406不可接受)但是,如果我將內容類型更改爲'application/x-www-form-urlencoded',那麼它確實有效。如何將JSON發送到MVC API(使用Ajax Post)

任何想法?

Ajax代碼摘錄:

$.ajax({ 
    type: "POST", 
    data: {"hello":"test"}, 
    url: "http://workingUrl/controller", 
    contentType : 'application/json', 
    cache: false, 
    dataType: "json", 
    ..... 

的Web API 2:

public IHttpActionResult Post(testModel hello) 
    { 
     /// do something here 
    } 

型號:

public class testModel 
    { 
     public string hello {get;set;} 

     public testModel() 
     { } 
    } 

提琴手:

HTTP/1.1 406 Not Acceptable (In the IDE, I have a breakpoint in the Post method which is not hit). 

我曾嘗試添加格式化到WebAPi.config,但沒有運氣

config.Formatters.Add(new JsonMediaTypeFormatter()); 

回答

0

與此JSON.stringify(TESTDATA)嘗試如下 -

var TestData = { 
    "hello": "test" 
}; 
$.ajax({ 
    type: "POST", 
    url: "/api/values", 
    data: JSON.stringify(TestData), 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    processData: true, 
    success: function (data, status, jqXHR) { 
     console.log(data); 
     console.log(status); 
     console.log(jqXHR); 
     alert("success..." + data); 
    }, 
    error: function (xhr) { 
     alert(xhr.responseText); 
    } 
}); 

輸出 -

enter image description here

0

我從來沒有指定contentType,當我這樣做,它始終工作。但是,如果它在您使用'application/x-www-form-urlencoded'時有效,那麼問題是什麼?

我確實在你的ajax中看到了一些東西。我會做這個

$.ajax({ 
type: "POST", 
data: {hello:"test"}, 
url: "http://workingUrl/controller/Post", 
cache: false)} 

對於數據,也許周圍的變量名引用將工作,但我從來沒有在那裏。

接下來,ajax調用中的url沒有控制器操作的名稱。那需要在那裏。