向Web API控制器发送请求时出现404错误 [英] 404 error when send request to web api controller

查看:459
本文介绍了向Web API控制器发送请求时出现404错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个ASP.NET MVC网站,正如标题所说,我正在尝试使用jquery向Web Api控制器发送POST请求,但始终收到404错误.疯狂的是,在.NET Framework 4.5中,完全相同的东西起作用,但是在.NET Framework 4.6.2中,实际上没有.我已经在Google中找到很多线程来解释可能会出错的地方,但是这些都不起作用.所以,这是我的代码:

Web Api类:

I am creating a ASP.NET MVC web site and as the title say i am trying to send a POST request to Web Api controller with jquery, but am always receiving a 404 error. The crazy thing is that in the .NET framework 4.5 the exact the same thing worked, but in the .NET framework 4.6.2 it really doesn''t. I ''ve found a lot of threads in google explaining what it might go wrong, but none of these worked. So, here is my code now:

The Web Api Class:

[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代码:



My jQuery code:

$(".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代码:



The Global.asax code:

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



如果有人可以帮助我,那将是很棒的.我已经花了6多个小时来解决这个错误,但我仍然找不到我做错了什么.

我尝试过的事情:

1)一些线程说Global.asax中调用"的顺序很重要,因此我更改了"



It would be great if someone could help me. I have spent over 6 hours on this bug, and i can''t still find out what i am doing wrong.

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);

"
的位置 在任何可能的地方.

2)在我的Web Api操作([Route("api/Cart/AddToCart")])中添加了路线属性,根据经验我知道这是多余的……并相应地更改了我的jQuery代码.

3)我没有添加属性,而是将Routes直接添加到Web Api Config.

4)我也尝试直接用邮递员打电话给Api(我当然删除了Authorize属性).

这些都不起作用.

''
in every possible place.

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.

3) Instead of adding attributes, i added to Routes directly to the Web Api Config.

4) I also tried to call the Api with postman directly(i removed the Authorize attribute of course).

None of these worked.

推荐答案

(.buy-button").click(function(){ 如果(@ User.Identity.IsAuthenticated.ToString().ToLower()=== true){
(".buy-button").click(function() { if (@User.Identity.IsAuthenticated.ToString().ToLower() === true) {


.ajax({ 网址:"/api/cart", 方法:"POST", 数据:
.ajax({ url: "/api/cart", method: "POST", data:


(this).next().val() }).done(function(){ alert(产品成功添加到购物车!"); }); } 别的 { window.location.href ="@ Url.Action("登录,"帐户)"; } });
(this).next().val() }).done(function() { alert("Product succesfully added to cart!"); }); } else { window.location.href = "@Url.Action("Login", "Account")"; } });



Global.asax代码:



The Global.asax code:

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



如果有人可以帮助我,那将是很棒的.我已经花了6多个小时来解决这个错误,但我仍然找不到我做错了什么.

我尝试过的事情:

1)一些线程说Global.asax中调用"的顺序很重要,因此我更改了"



It would be great if someone could help me. I have spent over 6 hours on this bug, and i can''t still find out what i am doing wrong.

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);

"
的位置 在任何可能的地方.

2)在我的Web Api操作([Route("api/Cart/AddToCart")])中添加了路线属性,根据经验我知道这是多余的……并相应地更改了我的jQuery代码.

3)我没有添加属性,而是将Routes直接添加到Web Api Config.

4)我也尝试直接用邮递员打电话给Api(我当然删除了Authorize属性).

这些都不起作用.

''
in every possible place.

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.

3) Instead of adding attributes, i added to Routes directly to the Web Api Config.

4) I also tried to call the Api with postman directly(i removed the Authorize attribute of course).

None of these worked.


这篇关于向Web API控制器发送请求时出现404错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆