我对 MVC5 和 Web API 相当陌生。 我正在尝试通过 ajax post 使用 Web API 服务。 我已经创建了该服务,当我通过浏览器 URL 调用它时,它就可以工作了。 通过 ajax 我收到 Method not allowed 错误。 我尝试了一些解决方案但没有成功。 禁用 WebDav。 呼叫来自同一域。
我创建了 Web 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);
}
});
}
尝试将
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);
}
});