问题
我正在创建一个 ASP.NET MVC 网站,正如标题所示,我正在尝试使用 jquery 向 Web Api 控制器发送 POST 请求,但总是收到 404 错误。疯狂的是,在 .NET Framework 4.5 中,完全相同的功能有效,但在 .NET Framework 4.6.2 中却不起作用。我在谷歌中发现了很多线程解释它可能会出错的地方,但这些都不起作用。所以,现在这是我的代码:
我的 Web 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 操作([Route("api/Cart/AddToCart")])中添加了路由属性,我从经验中知道这是多余的,并相应地更改了我的 jQuery 代码。
3)我没有添加属性,而是直接将路由添加到 Web Api 配置中。
4)我还尝试直接使用
Postman
调用Api(当然我首先从Web Api控制器中删除了Authorize属性)。
任何有关此问题的帮助都将不胜感激。谢谢。
我知道你谈到了更改路线配置,但我不知道具体细节 您是否也尝试过映射到操作
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: 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="Add to cart" data-RowId="@item.productID"
并在你的 jquery 中得到该值
var productID = $(this).attr('data-RowId');
并将其传递为
data: {productId : productID }
假设您有一个项目对象并且它具有 ProductID