我是MVC5和Web API的新手。 我正在尝试通过ajax帖子使用Web API服务。 iv'e创建了该服务,当我通过浏览器URL调用它时,它可以工作。 通过ajax我得到方法不允许错误。 我尝试了一些没有成功的解决方案。 禁用WebDav。 呼叫来自同一个域。
我已经创建了以下网络API:
public class ComicAPIController : ApiController
{
private List<ComicInput> ComicList = new List<ComicInput>(); //temp comic DB
public ComicAPIController()
{
ComicInput tmp = new ComicInput();
tmp.name = "Superman";
tmp.page = new List<Page>();
tmp.page.Add(new Page());
tmp.GenerateXML();
ComicList.Add(tmp);
tmp = new ComicInput();
tmp.name = "Spiderman";
tmp.GenerateXML();
ComicList.Add(tmp);
}
// GET: api/ComicAPI
public IEnumerable<ComicInput> Get()
{
return ComicList;
}
// GET: api/ComicAPI/5
public ComicInput Get(string id)
{
///will find in db
return ComicList.Find(e => e.name == id); ;
}
// POST: api/ComicAPI
public IEnumerable<ComicInput> Post(string value)
{
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
ComicInput objComic = new ComicInput();
objComic = jsonSerializer.Deserialize<ComicInput>(value);
ComicList.Add(objComic);
return ComicList;
}
// PUT: api/ComicAPI/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE: api/ComicAPI/5
public IEnumerable<ComicInput> Delete(string id)
{
ComicList.Remove(ComicList.Find(E => E.name == id));
return ComicList;
}
}
然后创建一个测试控制器并查看使用API。
function SendData()
{
jQuery.support.cors = true;
var myComic = {
name: "Superman Forever",
series: "Series",
author: "Stan Lee",
pages: {
image: "URL",
frames: {
topLeftX: 50,
topLeftY: 0,
width: 55,
height: 90,
rotation: {
degrees: 0,
centerX: 0,
centerY: 0
},
cropping: {
shape: "rect",
tlx: 0,
tly: 0,
w: 160,
h: 90,
color: "rgba(0,0,0,1)",
opacity: 1
},
filters: null,
transition: {
type: "move",
time: 1000
},
requireUserInput: false
}
}
};
$.ajax({
url: 'http://localhost/Web/api/ComicAPI',
type: 'POST',
data: JSON.stringify(myComic),
contentType: "application/json;charset=utf-8",
success: function (data) {
WriteResponse(data);
},
error: function (x, y, z) {
alert(x + '\n' + y + '\n' + z);
}
});
}
答案 0 :(得分:0)
尝试将dataType: "json",
添加到ajax调用中,如此...
$.ajax({
url: 'http://localhost/Web/api/ComicAPI',
type: 'POST',
data: JSON.stringify(myComic),
dataType: "json", // Add this here
contentType: "application/json;charset=utf-8",
success: function (data) {
WriteResponse(data);
},
error: function (x, y, z) {
alert(x + '\n' + y + '\n' + z);
}
});