简体   繁体   English

向Web API控制器发送请求时出现404错误

[英]404 error when send request to web api controller

The Problem 问题

I am creating a ASP.NET MVC web site and as the title say i am trying to send a POST request to a Web Api controller with jquery, but am always receiving a 404 error. 我正在创建一个ASP.NET MVC网站,正如标题所述,我正在尝试使用jQuery向Web Api控制器发送POST请求,但始终收到404错误。 The crazy thing is that in the .NET framework 4.5 the exact same thing worked, but in the .NET framework 4.6.2 it really doesn't. 疯狂的是,在.NET Framework 4.5中,完全相同的东西起作用了,但是在.NET Framework 4.6.2中,实际上却没有。 I have found a lot of threads in google explaining what it might go wrong, but none of these worked. 我在Google中发现了很多线程来解释可能会出错的地方,但是这些都不起作用。 So, here is my code now: 所以,这是我的代码:

My Web Api controller: 我的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);
    }
}

My jQuery code: 我的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")";
            }
        });

My Global.asax code: 我的Global.asax代码:

        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

What i have tried 我尝试过的

1) Some threads said that the order of the "calls" in the Global.asax matters, so i changed the position of RouteConfig.RegisterRoutes(RouteTable.Routes) in every possible way. 1)一些线程说Global.asax中“调用”的顺序很重要,因此我以各种可能的方式更改了RouteConfig.RegisterRoutes(RouteTable.Routes)的位置。

2) Added Route Attributes in my Web Api action([Route("api/Cart/AddToCart")]) which i know from experience that is redundant and changed my jQuery code accordingly. 2)在我的Web Api操作([Route(“ api / Cart / AddToCart”)])中添加了路由属性,根据经验,这是多余的,并相应地更改了我的jQuery代码。

3) Instead of adding attributes, i added the Routes directly to the Web Api Config. 3)我没有添加属性,而是将路由直接添加到Web Api Config。

4) I also tried to call the Api with Postman directly(i removed the Authorize attribute of course from the Web Api controller first). 4)我也尝试直接用Postman调用Api(我首先从Web Api控制器中删除了Authorize属性)。

Any help on this problem is appreciated. 感谢您提供有关此问题的任何帮助。 Thanks. 谢谢。

I know you talked about changing route config but as i dont know specifics have you tried mapping to action as well like 我知道您谈论过更改路由配置,但由于我不知道具体情况,您是否尝试过映射到操作以及

config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Routes.MapHttpRoute(name:“ DefaultApi”,routeTemplate:“ api / {controller} / {action} / {id}”,默认值:new {id = RouteParameter.Optional});

and then in ur ajax call 然后在您的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!");
            });

also if you would like to send productid there is one another way where you can assign that value to data-rowId attribute of button like 另外,如果您想发送productid,则可以使用另一种方法将该值分配给按钮的data-rowId属性,例如

HTML Code HTML代码

button type="button" value="Add to cart" data-RowId="@item.productID" 按钮type =“ button” value =“添加到购物车” data-RowId =“ @ item.productID”

and in ur jquery get that value as 并且在您的jquery中获取该值作为

var productID = $(this).attr('data-RowId'); var productID = $(this).attr('data-RowId');

and pass it as data: {productId : productID } 并将其作为数据传递:{productId:productID}

Assuming you have a item object and it has ProductID 假设您有一个item对象,并且它具有ProductID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM