![](/img/trans.png)
[英]Asp.Net MVC4 + Web API Controller Delete request >> 404 error
[英]404 error when send request to web api controller
问题
我正在创建一个ASP.NET MVC网站,正如标题所述,我正在尝试使用jQuery向Web Api控制器发送POST请求,但始终收到404错误。 疯狂的是,在.NET Framework 4.5中,完全相同的东西起作用了,但是在.NET Framework 4.6.2中,实际上却没有。 我在Google中发现了很多线程来解释可能会出错的地方,但是这些都不起作用。 所以,这是我的代码:
我的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 Config。
4)我也尝试直接用Postman
调用Api(我首先从Web Api控制器中删除了Authorize属性)。
感谢您提供有关此问题的任何帮助。 谢谢。
我知道您谈论过更改路由配置,但由于我不知道具体情况,您是否尝试过映射到操作以及
config.Routes.MapHttpRoute(name:“ 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代码
按钮type =“ button” value =“添加到购物车” data-RowId =“ @ item.productID”
并且在您的jquery中获取该值作为
var productID = $(this).attr('data-RowId');
并将其作为数据传递:{productId:productID}
假设您有一个item对象,并且它具有ProductID
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.