我正在使用一个需要通过jQuery AJAX调用的WebAPI方法。下面是用于AJAX调用的jQuery代码:
var BlogAndStoryComment = new Object();
BlogAndStoryComment.CommentID = 0;
BlogAndStoryComment.CommentUserName = userName;
BlogAndStoryComment.CommentText = commentText;
BlogAndStoryComment.CommentApprovedByUserID = 0;
BlogAndStoryComment.CommentDate = "date";
BlogAndStoryComment.HtmlComment = commentHtml;
BlogAndStoryComment.CommentIsSpam = 0;
BlogAndStoryComment.CommentIsApproved = 0;
BlogAndStoryComment.CommentEmail = email;
BlogAndStoryComment.CommentCount = 0;
BlogAndStoryComment.OnCommentID = 0;
BlogAndStoryComment.BlogID = blogID;
BlogAndStoryComment.SiteID = siteID;
BlogAndStoryComment.RowCount = 0;
$.ajax({
url: "http://localhost:55052/API/comments/GetAndPostBlogComments",
type: "POST",
data: JSON.stringify(BlogAndStoryComment),
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function(response) {},
error: function(jqXHR, textStatus, errorThrown) {},
failure: function(response) {}
});
这是我的WebAPI方法:
[Route("api/comments/GetAndPostBlogComments")]
[VersionedRoute("", 1)]
[ResponseType(typeof(HttpResponseMessage))]
[HttpPost]
public IHttpActionResult GetAndPostBlogComments([FromBody] BlogAndStoryComment comment)
{
}
当我从AJAX调用中调用此方法时,它正在点击error
函数,该函数为我提供statustext
或"error"
。但是,当我通过Postman调用时,方法正常工作。有什么问题?
答案 0 :(得分:0)
对于简单类型,在服务器端:
public void Post([FromBody]string name)
{
}
在客户端,您只需定义是否要以json格式发送:
var dataJSON = "test";
$('#testPostMethod').bind("click", GeneralPost);
function GeneralPost() {
$.ajax({
type: 'POST',
url: '/api/comments/GetAndPostBlogComments',
//url: '../api/comments/GetAndPostBlogComments',
//url: '~/api/comments/GetAndPostBlogComments',
data: JSON.stringify(dataJSON),
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
}
如果你想让它在复杂类型中工作,从服务器端你应该定义:
public class RecipeInformation
{
public string name { get; set; }
}
public class ValuesController : ApiController
{
public void Post(RecipeInformation information)
{
}
}
从客户端:
var dataJSON = { name: "test" };
$('#testPostMethod').bind("click", GeneralPost);
function GeneralPost() {
$.ajax({
type: 'POST',
url: '/api/comments/GetAndPostBlogComments',
//url: '../api/comments/GetAndPostBlogComments',
//url: '~/api/comments/GetAndPostBlogComments',
data: JSON.stringify(dataJSON),
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
}
答案 1 :(得分:0)
你可以尝试做这样的事情并使用jquery param方法
var postData = {
name : 'name'
}
$('#testPostMethod').bind("click", GeneralPost);
function GeneralPost() {
$.ajax({
type: 'POST',
url: '../api/comments/GetAndPostBlogComments',
//url: '~/api/comments/GetAndPostBlogComments',
data: $.param(postData,true),
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
}