我刚刚构建了我的第一个ASP.NET Web API。我现在正在尝试将一个对象发送到我的API,但不知道该怎么做。
到目前为止,这是我的代码:
Employee employee = new Employee();
employee.Id = 1234;
employee.FirstName = "John";
employee.LastName = "Smith";
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://myapi.mydomain.com");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token.AccessToken);
**// How do I send my employee object to the API?**
HttpResponseMessage response = await client.GetAsync("api/mycontroller/myaction");
if (response.IsSuccessStatusCode)
{
var someObject = await response.Content.ReadAsAsync<myObjectType>();
}
}
答案 0 :(得分:0)
您需要做的是对API端点执行POST并将您的员工对象序列化为json对象,如下所示:
var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
response = await client.PostAsJsonAsync("api/products", gizmo);
if (response.IsSuccessStatusCode)
{
// Get the URI of the created resource.
Uri gizmoUrl = response.Headers.Location;
}
目前您的现有代码只是执行GET请求。
HttpResponseMessage response = await client.GetAsync("api/mycontroller/myaction");
我强烈建议您take a look at this article明确强调如何通过C#调用Web API端点。
我希望这会有所帮助。