【问题标题】:AcceptVerbs not working in Web API ControllerAcceptVerbs 在 Web API 控制器中不起作用
【发布时间】:2012-09-15 01:07:54
【问题描述】:

我正在尝试通过 ajax 请求调用 Web API 控制器中的操作,如下所示

$.ajax({
            url: "/api/GuestPartyAPI/" + cerid,
            type: "GETAD",
            async: false,
            data: { Id: id, Name: name, NeedsHotel: needshotel_bool, TableNo: tableno, QR_CodeImage: qrcodeimage,
                AddressLabel: addresslabel, Address_1: address1, Address_2: address2, City: city, State: state,
                PostalCode: postalcode, Country: country, Email: email, Phone: phone
            },
            dataType: "json" 
        }).fail(function (jqXHR, textStatus) {
            console.log(jqXHR);
            console.log(textStatus);
            //alert("cerid " + cerid);
            //alert("Request failed: " + textStatus);
        });

Controller中的Action如下

[AcceptVerbs("GETAD")]
    public HttpResponseMessage GetGuestPartyCer(int cerid, GuestParty guestparty) 
    {

        if (ModelState.IsValid)
        {
            db.GuestParties.AddObject(guestparty);
            db.SaveChanges();

            CeremonyGuestParty ceremonygp = new CeremonyGuestParty(); //create a CeremonyGuestParty entry to link ceremony and guestparty
            ceremonygp.CeremonyId = cerid;
            ceremonygp.GuestPartyId = guestparty.Id;
            db.CeremonyGuestParties.AddObject(ceremonygp);
            db.SaveChanges();

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, guestparty);
            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = guestparty.Id }));
            return response;
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }
    }

同一个控制器中的一个类似 Action 正在通过一个类似的 ajax 请求处理 [AcceptVerbs("GETAC")],但不是这个,甚至没有将动词“GETAD”更改为其他内容。

这里是代码 $.ajax({ url: "/api/GuestPartyAPI/" + id, 类型:“GETAC”, 异步:假, 数据类型:“json”});

【问题讨论】:

  • 你能把$.ajax通话的代码贴出来吗?
  • 这里是代码 $.ajax({ url: "/api/GuestPartyAPI/" + id, type: "GETAC", async: false, dataType: "json" });
  • 您使用哪种浏览器?您的 WebApiConfig 路由配置如何?您可能需要将您的操作更改为GetGuestPartyCer(int id, GuestParty guestparty),注意int id 以匹配默认路由。
  • 通过更改为“int id”,它起作用了。谢谢 nemesv。

标签: javascript asp.net-mvc-4 asp.net-web-api


【解决方案1】:

您的问题与使用的AcceptVerbs 无关,但路由和操作参数匹配如何工作:

如果动作参数来自路由参数,则参数名称必须与您在路由中定义的参数名称匹配。

所以如果你使用默认路由你的 ApiControllers:

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

请注意,您的路由参数称为{id}

因此在您的操作中您需要使用相同的名称id 以便框架可以进行匹配。

只需将您的操作签名 cerid 更改为 id 即可:

public HttpResponseMessage GetGuestPartyCer(int id, GuestParty guestparty)

【讨论】:

    猜你喜欢
    • 2015-08-10
    • 2017-12-28
    • 2013-11-23
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-16
    • 2023-03-12
    相关资源
    最近更新 更多