2014-01-24 47 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没有控制器操作的名称。那需要在那里。