【问题标题】:How to call web api with data如何使用数据调用 web api
【发布时间】:2014-07-04 10:39:20
【问题描述】:

在我的 web api 控制器中,我有两个具有以下结构的函数

public HttpResponseMessage Post(CountryDto country)
 {
    var countries = _countryAppService.RegisterNewCountry(country);
    var message = Request.CreateResponse(HttpStatusCode.Created, countries);
    return message;
 }

public HttpResponseMessage Post(int countryId, StateDto state)
{
    var country = _countryAppService.AddNewState(state, countryId);
    var message = Request.CreateResponse(HttpStatusCode.Created, country);
    return message;
}

我需要调用 post 的第二个重载版本,我使用 fiddler 和以下 http 请求详细信息进行了尝试

POST http://localhost:51830/api/Country/ HTTP/1.1
User-Agent: Fiddler
Host: localhost:51830
Content-Type: application/json; charset=utf-8
Content-Length: 63

{"countryId":5,"state":{"StateName":"Dallas","StateCode":"DA"}}

但它调用的是第一个重载帖子而不是第二个帖子,我缺少什么以及如何使用 fiddler 调用第二个帖子

【问题讨论】:

  • 认为这个问题与模型绑定器有关(但不确定)。一种解决方法是使用不同的路由,例如使用attribute routingActionName 属性。

标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-4 asp.net-web-api fiddler


【解决方案1】:

WebAPI(也包括 MVC)不支持重载。

但是你可以使用attribute-based路由来实现你想要的,即:

[Route("api/country/add")]
public HttpResponseMessage AddCountry(CountryDto country)

[Route("api/country/addstate")]
public HttpResponseMessage AddCountry(int countryId, StateDto state)

您需要确保在配置中的其余路由之前调用config.MapHttpAttributeRoutes();(即:config.Routes.MapHttpRoute...

【讨论】:

    【解决方案2】:

    需要在方法二的StateDto参数上指定[FromBody]属性。

    http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-02
      • 2018-09-07
      • 2021-08-25
      • 2013-10-17
      • 2012-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多