我正在尝试从我的html客户端调用api。它给了我内部服务器错误,但当我尝试使用邮差时,它的工作原理。
这是我的api代码
[AcceptVerbs("POST")]
public dynamic Add(string post,string title, string user)
{
if (post == null)
throw new Exception("Post content not added");
if (title == null)
throw new Exception("Post title not added");
var u = UserManager.FindByEmailAsync(user);
Blog blog = Blog.Create(u.Result.Account.RowKey, post, title).Save();
return new
{
id = blog.Id
};
}
我的html客户端就像这样
var d = {
post: post,
title: title,
user: user
}
$.ajax({
type: 'POST',
url: apiUrl + 'Blog/Add',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: JSON.stringify(d)
}).done(function (data) {
console.log(data);
}).fail(function (error) {
});
这是我的路由api配置代码
config.Routes.MapHttpRoute(
name: "RPCApi",
routeTemplate: "{controller}/{action}/{id}",
defaults: new
{
id = RouteParameter.Optional
},
constraints: new
{
subdomain = new SubdomainRouteConstraint("api")
}
);
任何人都可以帮助我并解释一下为什么它与邮递员合作而不是我的html客户端?
答案 0 :(得分:1)
这是因为你的json代表一个具有3个属性的对象。你的控制器不带一个对象,需要3个字段。使用请求消息发送有效负载时,您必须将其作为对象发送,并且您的Web api必须具有可以将请求消息反序列化的单个模型。更改以下内容将起作用,您的javascript将保持不变。
有关其原因以及实现相同目标的其他方式的详细信息,请参阅Angular2 HTTP Post ASP.NET MVC Web API上的上一个答案 (忽略标题中的客户端框架,答案特定于Web API 2 )
<强>模型强>
public class SomethingToPost{
[Required]
public string Post{get;set;}
[Required]
public string Title{get;set;}
public string User{get;set;}
}
<强>控制器强>
[AcceptVerbs("POST")]
public dynamic Add(SomethingToPost postThing)
{
// validation on ModelState
// action code
}
答案 1 :(得分:0)
这可能是因为返回类型dynamic
。考虑到int
的类型为id
Int32
[AcceptVerbs("POST")]
public int Add(string post,string title, string user)
{
if (post == null)
throw new Exception("Post content not added");
if (title == null)
throw new Exception("Post title not added");
var u = UserManager.FindByEmailAsync(user);
Blog blog = Blog.Create(u.Result.Account.RowKey, post, title).Save();
return blog.Id;
}