【发布时间】:2018-09-07 22:17:22
【问题描述】:
我有一个异步函数,用于向服务器发送请求消息。函数如下:
class http
{
public async Task<string> HttpRequest()
{
HttpRequestMessage request = GetHttpRequestMessage();
var str1 = await ExecuteRequest(request);
return str1;
}
private async Task<string> ExecuteRequest(HttpRequestMessage request)
{
string result = string.Empty;
try
{
using (HttpClient client = new HttpClient())
{
var responses = await client.SendAsync(request);
responses.EnsureSuccessStatusCode();
result = await responses.Content.ReadAsStringAsync();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return result;
}
private const string _DataTypeJson = @"application/json";
private HttpRequestMessage GetHttpRequestMessage()
{
Dictionary<string, string> headers = GetHeadersUsedForToken();
string str = "https://test.com//tokens";
Uri uri = new Uri(str);
HttpRequestMessage request = new HttpRequestMessage
{
RequestUri = uri,
};
if (null != headers)
{
foreach (string key in headers.Keys)
{
request.Headers.Add(key, headers[key]);
}
}
// Hard code Accpt type is Json
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(_DataTypeJson));
request.Method = HttpMethod.Get;
return request;
}
private Dictionary<string, string> GetHeadersUsedForToken()
{
return new Dictionary<string, string>
{
{ "id", "abc" },
{ "secret", "***" }
};
}
}
这个函数在 console 项目中运行良好,但是当我尝试将此函数移动到 WCF 服务,并尝试在服务中调用 HttpRequest() 函数时,
[ServiceContract]
public interface IService1
{
[OperationContract]
Task<string> GetData();
}
public class Service1 : IService1
{
public Task<string> GetData()
{
http test = new http();
return test.HttpRequest();
}
}
抛出异常:
Message An error occurred while sending the request.
InnerException {"The underlying connection was closed: An unexpected error occurred on a send."}
【问题讨论】:
-
顺便提一下,过早调用
Result会破坏async的全部目的 -
还有死锁..
-
@MickyD,谢谢您的回复。该函数只是一个隐藏一些细节的演示函数。我的核心问题是该功能在 WCF 中不起作用。你能帮忙吗?
-
@PauloMorgado,感谢您的回复。对我的问题有什么建议吗?
-
我们如何知道哪些代码是真实的?发布您的实际代码。祝你好运!
标签: c# wcf asynchronous async-await httprequest