与MVC5消费Web服务WebAPI - 无法连接到服务
所以我试图连接到一个Web服务来检索JSON并将其显示到我的视图。但是任何时候我运行代码,我收到一个错误说:与MVC5消费Web服务WebAPI - 无法连接到服务
"Unable to connect to the remote server."
当我浏览到在浏览器中的Web服务URL它会显示一个JSON字符串只是它应该的方式。
我的控制器类Tweets.cs:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TwitterClientMVC.Controllers
{
public class Tweets
{
public Tweet[] results;
}
public class Tweet
{
[JsonProperty("atristName")]
public string Artist { get; set; }
[JsonProperty("trackName")]
public string TrackName { get; set; }
}
}
我HomeController.cs类:
public class HomeController : Controller
{
public ActionResult Index()
{
Tweets model = null;
var client = new HttpClient();
var task = client.GetAsync("http://itunes.apple.com/search?term=metallica")
.ContinueWith((taskwithresponse) =>
{
try
{
**var response = taskwithresponse.Result;** Fails here
var readtask = response.Content.ReadAsAsync<Tweets>();
readtask.Wait();
model = readtask.Result;
}
catch (AggregateException e)
{
e.ToString();
}
});
task.Wait();
return View(model.results);
}
正如我已经建立了这个以下的教程和非常新的网络API,我没有想法为什么它会抛出一个错误。
想法?
我发现很少很好的教程展示了如何使用webAPI2简单的web服务,因为它是一个新概念。我也找不到为什么我会得到这个错误。
编辑:
忘了提,我运行在本地主机上这个项目,不知道这是相关的。
编辑2:
精确例外:
{"An error occurred while sending the request."}
的InnerException:
{"Unable to connect to the remote server"}
的InnerException:
{"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 23.3.162.217:80"}
我试过几个不同的URL,他们都跑在b rowser和没有运行在我的程序,所以我必须错过什么?
如果你看看来自iTunes的响应标题,你可以看到内容类型不是application/json
它是text/javascript
。
刚刚自己运行你的代码,我不相信当你访问响应时抛出异常。当您尝试阅读响应主体时,它会抛出,因为内置的媒体类型格式化程序不支持text/javascript
。
您可以将不支持的媒体类型添加到JsonMediaTypeFormatter
,或者(也许更简单的选项),您可以只读取响应主体作为字符串,然后自己执行JSON反序列化。
此外,异步/等待是你的朋友。你会发现它使异步API的工作变得更容易:
public async Task<ActionResult> Index()
{
using (var client = new HttpClient())
{
var response = await client.GetAsync("http://itunes.apple.com/search?term=metallica");
var json = await response.Content.ReadAsStringAsync();
var tweets = JsonConvert.DeserializeObject<Tweets>(json);
return View(tweets);
}
}
虽然这不是原来的问题,但只要我解决了超时错误,您对类型错误是正确的。超时错误是由于网络保护发生的,因为Visual Studio的某些实例不能使用网络凭证运行。感谢你的回答! – Blunderfest
@Malcoda - 你是如何解决超时的原始问题的?我在MVC5应用程序中看到一个非常类似的东西。相同的请求/响应代码在控制台应用程序中正常工作。 – Ron
我安装了Fiddler来调试一些问题,现在只要我尝试通过Visual Studio连接到Web服务,我必须让Fiddler打开并运行。 – Blunderfest
你会得到什么异常? –
@JeremyHolovacs增加了例外。我不能为我的生活弄清楚,我也尝试了几种不同的连接方式,并且每次都得到相同的错误。显然,我想做的事情是我不明白的。 – Blunderfest