Reputation: 5461
I have a Web API application which exposes certain async methods, such as:
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);
}
I also have a class library that consumes this API with System.Net.WebRequest like this:
var request = (HttpWebRequest)WebRequest.Create(url);
var response = await request.GetResponseAsync();
Does the response need to be retrievend async? If so, why? Or can I also use request.GetResponse();
.
I used the GetResponse
before which would sometimes throw a 500 error ( An asynchronous module or handler completed while an asynchronous operation was still pending
). Once I changed it to GetResponseAsync()
, I stopped receiving this error.
EDIT: Code that sometimes throws a 500 error
I had the web api method stripped down to (just to check whether the 500 error was business logic or something else). Note: this is after changing the consumer to async (first function is the consumer, then the api method):
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;
}
Upvotes: 1
Views: 335
Reputation: 149538
Does the response need to be retrievend async? If so, why?
No, it doesn't. You need to separate how the server-side operates and how the client queries your endpoint. When you expose a method which is async Task
, you state that in your server-side calls, you're making async calls. This is transparent to the caller, all he gets is an API endpoint, he doesn't have any knowledge of your internal implementation.
Remember, even if you use async
on the server-side, the request will only return to the caller once complete.
Upvotes: 2