我收到错误" 无法从int转换为system.net.http.httpcompletionoption。"
我是构建Web API的新手,我只是尝试创建一个简单的GET请求,该请求接受一个int id并转到我的API中的get方法,该方法接受一个int并返回具有该ID的产品。我将在下面发布我的代码以及我在哪里收到错误。
public ActionResult Details(int id)
{
Contact contact = new Contact();
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:56194/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
//Im getting error on line below right after client.GetAsync on the id after the uri
HttpResponseMessage response = client.GetAsync("api/contacts", id).Result;
if (response.IsSuccessStatusCode)
{
contact = response.Content.ReadAsAsync<Contact>().Result;
}
return View(contact);
}
我的API方法目前位于
之下[ResponseType(typeof(contact))]
public IHttpActionResult Getcontact(int id)
{
contact contact = db.contacts.Find(id);
if (contact == null)
{
return NotFound();
}
return Ok(contact);
}
谢谢,我很感激任何帮助都无法在Google上找到有关遇到此错误的人。
答案 0 :(得分:0)
如果您查看GetAsync的文档,则应在第二个参数中传递枚举值,即HttpCompletionOption enum
。
因此,如果您想使用int,那么您应该将其强制转换为HttpCompletionOption
。
你的代码应该是:
HttpResponseMessage response = client.GetAsync("api/contacts",
(HttpCompletionOption)id).Result;
您的ID似乎是为了获取联系,那么您应该这样做:
HttpResponseMessage response = client.GetAsync("api/contacts/" + id,
HttpCompletionOption.ResponseContentRead).Result;