Consume Web API haing Action methods with custom n

2019-09-08 17:55发布

问题:

I am trying to consume web api in which action method names are custome like CreateCustomer(..), GetCustomer(...). These are annotated with [HttpPost]/[HttpGet]. I am not sure how to consume it using HttpClient(). If is set as following and me a call

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;

It throws 404. Where as if i use fiddler and send arequest to http://host/directory/api/customer with JSON customer object it works perfectly

What exactly am i missing here? Do i need to user POST and GET as methods?

回答1:

you need to configure your route to include the action like api/{controller}/{action}/{id} and make call like api/customer/CreateCustomer

from C#,

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