![](/img/trans.png)
[英]How to call a Web API service from MVC using windows authentication?
[英]How to call a REST API from a Windows Service
我正在尝试从 Windows 服务调用 Rest API。 我以前从未尝试过。 我不知道为什么我不能打这个电话。
我的代码:
string urlParameter = "posts/1";
var client = new HttpClient();
client.BaseAddress = new Uri("http://jsonplaceholder.typicode.com/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync(urlParameter).Result;
if (response.IsSuccessStatusCode)
{
var dataObj = response.Content.ReadAsAsync<IEnumerable<MyType>>().Result;
}
我收到以下错误:
消息:发送请求时出错。
内部异常消息:{“底层连接已关闭:连接意外关闭。”}
System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult) 处的内部异常堆栈跟踪
在 System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
此错误是在以下行上生成的:
HttpResponseMessage response = client.GetAsync(urlParameter).Result;
任何建议,将不胜感激。
编辑:(更新代码)
string urlParameter = "posts/1";
var client = new HttpClient();
client.BaseAddress = new Uri("http://jsonplaceholder.typicode.com/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
//var response = await client.GetAsync(urlParameter);
var task = client.GetAsync(urlParameter);
task.Wait();
var response = task.Result;
if (response.IsSuccessStatusCode)
{
var dataObj = response.Content.ReadAsAsync<IEnumerable<MyType>>().Result;
}
}
catch (Exception ex)
{
string a = ex.Message;
string b = ex.ToString();
}
编辑2:(仍然得到同样的错误)
private static async void TestAPI2()
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Get", "application/json");
var response = await client.GetAsync("http://jsonplaceholder.typicode.com/posts/1");
string context = await response.Content.ReadAsStringAsync();
}
}
你的问题是...
var response = client.GetAsync(urlParameter);
...返回一个任务,您需要先等待它完成。
打这个电话的最干净的方法是这样的......
var response = await client.GetAsync(urlParameter);
...这需要代码以这样的异步方法运行...
public async Task Foo()
{
var response = await client.GetAsync(urlParameter);
}
...或者您可以简单地告诉编译器使用 ...
var task = client.GetAsync(urlParameter);
task.Wait();
var response = task.Result;
……或者更紧凑的版本可能是使用这样的延续……
var result = await client.GetAsync(urlParameter)
.ContinueWith(t => t.Result.Content.ReadAsAsync<IEnumerable<MyType>>())
.Unwrap();
...这将执行请求,然后当请求返回时为您异步解析它并解包任务返回“内部结果”,因为此代码创建了一个 Task>> 并且您只想要 IEnumerable 所以等待解包的任务让你2个任务一个接一个执行的结果:)
...我查看了您的特定代码并在新的控制台应用程序中运行该代码,请将其更新为...
class MyType
{
public int userId { get; set; }
public int id { get; set; }
public string title { get; set; }
public string body { get; set; }
}
static void TestAnApiCall()
{
string urlParameter = "posts/1";
var client = new HttpClient();
client.BaseAddress = new Uri("http://jsonplaceholder.typicode.com/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
//var response = await client.GetAsync(urlParameter);
var task = client.GetAsync(urlParameter);
task.Wait();
var response = task.Result;
if (response.IsSuccessStatusCode)
{
var readTask = response.Content.ReadAsAsync<MyType>();
readTask.Wait();
var dataObj = readTask.Result;
Console.WriteLine(JsonConvert.SerializeObject(dataObj));
}
}
catch (Exception ex)
{
string a = ex.Message;
string b = ex.ToString();
}
}
是的,它确实在“控制台应用程序”中工作,但是相同的代码在窗口服务中不起作用。 – 约翰·多伊
想回复此评论。 我确实遇到过类似的问题。 Rest API 无法从 Windows 服务进行调用,但它在控制台应用程序中工作。 显示为
{System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: 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 80.228.241.59:443
at System.Net.Sockets.Socket.InternalEndConnect(IAsyncResult asyncResult)
at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
--- End of inner exception stack trace ---
由于防火墙问题,这一切都发生在我身上。 最后能够使用 RestClient 中的代理设置解决这个问题并且它起作用了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.