【问题标题】:Consume Web API haing Action methods with custom name使用具有自定义名称的 Web API 具有 Action 方法
【发布时间】:2015-07-08 17:23:32
【问题描述】:

我正在尝试使用操作方法名称为自定义的 Web api,例如 CreateCustomer(..)、GetCustomer(...)。这些用 [HttpPost]/[HttpGet] 注释。我不确定如何使用 HttpClient() 来使用它。如果设置如下和我一个电话

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://host/directory/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.PostAsJsonAsync("api/customer", cutomerObj).Result;

它抛出 404。好像我使用 fiddler 并将请求发送到 http://host/directory/api/customer 与 JSON 客户对象它完美地工作

我到底错过了什么?我需要使用 POST 和 GET 作为方法吗?

【问题讨论】:

  • 你需要配置你的路由以包含action,比如api/{controller}/{action}/{id},并像api/customer/CreateCustomer一样拨打电话。
  • 这篇文章有帮助吗?
  • 我已经确定了我的路线

标签: asp.net asp.net-mvc asp.net-web-api httpclient


【解决方案1】:

您需要配置您的路由以包含 actionapi/{controller}/{action}/{id} 并像 api/customer/CreateCustomer 一样拨打电话

来自 C#,

var t = new HttpClient().GetAsync("http://localhost:63154/api/UserApi/CreateCustomer").Result.Content.ReadAsStringAsync().Result;

【讨论】:

  • 谢谢。有效。因为我向该方法发布了一个自定义类。我必须进行以下更改 var response = client.PostAsJsonAsync("host/directory/api/customer/createcustomer", customerObj).Result;
  • 没错,就像HttpContent
猜你喜欢
  • 2018-09-21
  • 2023-04-10
  • 2017-05-08
  • 2020-08-20
  • 2012-03-23
  • 2020-09-19
  • 1970-01-01
  • 1970-01-01
  • 2012-03-12
相关资源
最近更新 更多