[英]ASP.NET WEB API do i need async client
我有一个Web API应用程序,它公开了某些异步方法,例如:
public async Task<HttpResponseMessage> Put(string id){
var data = await Request.Content.ReadAsStringAsync();
//do something to put data in db
return Request.CreateResponse(HttpStatusCode.Ok);
}
我还有一个类库,它通过System.Net.WebRequest使用此API,如下所示:
var request = (HttpWebRequest)WebRequest.Create(url);
var response = await request.GetResponseAsync();
是否需要异步获取响应? 如果是这样,为什么? 或者我也可以使用request.GetResponse();
。
我使用了GetResponse
在此之前有时会抛出500错误( An asynchronous module or handler completed while an asynchronous operation was still pending
)。 一旦将其更改为GetResponseAsync()
,我就停止接收此错误。
编辑:有时会引发500错误的代码
我将Web api方法简化为(只是检查500错误是业务逻辑还是其他原因)。 注意:这是在将使用者改为异步之后(第一个功能是使用者,然后是api方法):
public HttpWebResponse(GetApiResponseForPut(string url, string putData, NameValueCollection headers)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.CookieContainer = _cookieContainer;
request.Method = "PUT";
if (headers != null)
{
request.Headers.Add(headers);
}
var encoding = new ASCIIEncoding();
var byte1 = new byte[0];
if (putData != null)
{
byte1 = encoding.GetBytes(putData);
}
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byte1.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(byte1, 0, byte1.Length);
requestStream.Close();
var response = await request.GetResponseAsync();
return (HttpWebResponse)response;
}
public async Task<HttpResponseMessage> Put(string id)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
return response;
}
是否需要异步获取响应? 如果是这样,为什么?
不,不是。 您需要分开服务器端的操作方式以及客户端如何查询端点。 当公开async Task
方法async Task
,说明在服务器端调用中正在进行异步调用。 这对调用者是透明的,他得到的只是一个API端点,他不了解您的内部实现。
请记住,即使您在服务器端使用async
,请求也只会在完成后返回给调用方。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.