【发布时间】:2017-09-15 12:16:09
【问题描述】:
我正在尝试从我的 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 客户端一起工作吗?
【问题讨论】:
-
您收到什么错误?
-
未找到。 404. 基本上是无法到达api端点。
-
不要抛出
Exception- 这将导致 500。在这些情况下您应该返回 400 结果。 -
好的,但这不是问题,因为它是由邮递员工作的。我从客户端调用 api 的方式有问题。
-
apiUrl + 'Blog/Add'是否生成正确的 URL?
标签: c# asp.net-web-api