首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AcceptVerbs在Web API控制器中不起作用

AcceptVerbs在Web API控制器中不起作用
EN

Stack Overflow用户
提问于 2012-09-23 14:57:11
回答 1查看 1.4K关注 0票数 1

我尝试通过ajax请求调用Web API Controller中的Action,如下所示

代码语言:javascript
复制
$.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);
        });

控制器中的操作如下所示

代码语言:javascript
复制
[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);
        }
    }

同一个控制器中的一个类似的操作是通过一个类似的ajax请求使用AcceptVerbs("GETAC"),但不是这个请求,甚至不是通过将动词"GETAD“更改为其他东西。

代码$.ajax({ url:"/api/GuestPartyAPI/“+ id,type:"GETAC",async: false,dataType:"json”})

EN

回答 1

Stack Overflow用户

发布于 2012-09-23 16:39:00

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

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

因此,如果您使用默认路由您的ApiControllers:

代码语言:javascript
复制
config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

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

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

只需将您的操作签名cerid更改为id,它应该会起作用:

代码语言:javascript
复制
public HttpResponseMessage GetGuestPartyCer(int id, GuestParty guestparty)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12550366

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档