HTTP错误完成
问题描述:
我得到一个错误“不能从int转换为system.net.http.httpcompletionoption。”HTTP错误完成
我是新来构建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);
}
谢谢,我希望得到任何帮助不能找到很多关于谷歌有关的人遇到这个错误。
答
如果你看看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;