2017-07-30 78 views
0

我知道有很多问题/回答有关此,所以我想我错过了一些东西。我在这里看不到问题。任何帮助表示赞赏。'在与请求匹配的控制器上找不到任何操作。'在webforms应用程序试图使WebAPI调用

Ajax调用:

$('#btnGetShipMethods').click(function() { 
     var basketguid = 'abcd'; 
     var data = { 
      BasketGuid: basketguid 
     }; 
     data = JSON.stringify(data); 
     $.ajax({ 
      type: "POST", 
      url: "/api/Checkout/GetShipMethods", 
      data: data, 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      success: function (msg) { 
       alert('Success: ' + msg); 
      }, 
      error: function (error) { 
       alert("Failed " + error.responseText); 
      } 
     }); 
    }); 

控制器:

public class CheckoutController : ApiController 
{ 
    [HttpPost] 
    [Route("api/Checkout/GetShipMethods")] 
    public string GetShipMethods(string BasketGuid) { 
     var basket = DbBasket.GetBasket(BasketGuid); 

     return BasketGuid; 
    } 
} 

Global.asax中的Application_Start

 GlobalConfiguration.Configure(config => { 
      config.MapHttpAttributeRoutes(); 
      config.Routes.MapHttpRoute(
      name: "DefaultApi", 
      routeTemplate: "api/{controller}/{id}", 
      defaults: new { id = System.Web.Http.RouteParameter.Optional }); 
     }); 

回答

0

作出POST请求,并发送一个身体,你基本上是创建一个object与当一定数量的属性。在这种情况下,您发送的房产为object,但您只接受.Net(而不是object)的房产。

要解决此问题,您需要创建一个包含BasketGuid属性的模型,并在您的端点中接受它。像下面这样。

... 
[HttpPost] 
[Route("api/Checkout/GetShipMethods")]  
public string GetShipMethods([FromBody]Basket basket) { 
... 

Basket类会是这个样子

public class Basket 
{ 
    public string BasketGuid {get; set;} 
} 
+0

是的,我试过了。该调用然后成功,但参数BasketGuid为空。 –

+0

尝试使用属性BasketGuid创建模型并将其作为参数接受。 – jeanfrg

+0

@BrandonSpilove我已经更新了我的答案。检查出来,让我知道如果有帮助。 – jeanfrg

相关问题