问题
我正在创建一个ASP.NET MVC网站,并且标题上说我正在尝试使用jquery向Web Api控制器发送POST请求,但是我总是收到404错误。疯狂的是,在.NET framework 4.5中,完全相同的东西是有效的,但在.NET框架4.6.2中它确实没有。我在google中找到了很多线程来解释它可能出错的地方,但这些都没有奏效。所以,现在是我的代码:
我的网络Api控制器:
[Authorize]
public class CartController : ApiController
{
private ApplicationDbContext _context;
public CartController()
{
_context = new ApplicationDbContext();
}
[HttpPost]
public IHttpActionResult AddToCart(string productId)
{
if (!ModelState.IsValid || !ItemIsValid(productId))
return BadRequest();
var newCartItem = new ShoppingCartItem
{
ProductId = productId,
UserId = User.Identity.GetUserId()
};
_context.ShoppingCartItems.Add(newCartItem);
_context.SaveChanges();
return Ok();
}
private bool ItemIsValid(string productId)
{
return Enumerable.Any(_context.Products, contextproduct => contextproduct.Id.ToString() == productId && contextproduct.NumberAvailable > 0);
}
}
我的jQuery代码:
$(".buy-button").click(function() {
if (@User.Identity.IsAuthenticated.ToString().ToLower() === true) {
$.ajax({
url: "/api/cart",
method: "POST",
data: $(this).next().val()
}).done(function() {
alert("Product succesfully added to cart!");
});
} else {
window.location.href = "@Url.Action("Login", "Account")";
}
});
我的Global.asax代码:
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
我尝试了什么
1)有些线程表示"调用"在Global.asax很重要,所以我改变了RouteConfig.RegisterRoutes(RouteTable.Routes)
的位置
以各种可能的方式。
2)在我的Web Api动作中添加了路由属性([路由(" api / Cart / AddToCart")])我从经验中知道这是多余的并相应地改变了我的jQuery代码。
3)我没有添加属性,而是直接将路由添加到Web Api配置中。
4)我还尝试直接用Postman
调用Api(我当然首先从Web Api控制器中删除了Authorize属性)。
对此问题的任何帮助表示赞赏。感谢。
答案 0 :(得分:0)
我知道你谈过改变路线配置,但我不知道具体细节 你有没有尝试映射到行动,如
config.Routes.MapHttpRoute( 名称:“DefaultApi”, routeTemplate:“api / {controller} / {action} / {id}”, 默认值:new {id = RouteParameter.Optional} );
然后在你的ajax电话中
$.ajax({
url: "api/Cart/AddToCart",
type: "POST",
contentType: "application/json",
data: JSON.stringify($(this).next().val())
}).done(function() {
alert("Product succesfully added to cart!");
});
如果您想发送productid,还有另一种方法可以将该值分配给按钮的data-rowId属性,如
HTML代码
button type =“button”value =“添加到购物车”data-RowId =“@ item.productID”
并在你的jquery中获取该值为
var productID = $(this).attr('data-RowId');
并将其传递给 data:{productId:productID}
假设您有一个item对象并且它有ProductID