I'm a bit confused with HttpResponseMessage and Task<HttpResponseMessage>.
If I'm using the HttpClient method PostAsync() to post data I need to give the Web Service method the Task<HttpResponseMessage> instead of HttpResponseMessage as return value as far as I understood things.
If I use Request.CreateResponse(HttpStatusCode.Forbidden, myError.ToString());
then I'm only getting the Response message object but not the Task object.
So my question here is how do I have to create the Fitting return for async calls to web api methods?
(thus are my understandings there correct and if so how to best transform the message object int a Task<HttpResponseMessage> object)
The original code:
public HttpResponseMessage DeviceLogin(MyDevice device)
{
EnummyError myError = EnummyError.None;
// Authenticate Device.
myError = this.Authenticate(device);
if (myError != EnummyError.None)
{
return Request.CreateResponse(HttpStatusCode.Forbidden, myError.ToString());
}
}
The updated Method header:
public Task<HttpResponseMessage> DeviceLogin(MyDevice device)
Web Api 2 has these abstraction classes which are now recommended to use. You can still use HttpResponseMessage (easier to follow for beginners, in my opinion), but Web Api 2 recommends using IHttpActionResult.
As for the return type, just did what you did before. Task<T> works automagically that way.
You also might want to check if this.Authenticate() has an async variant.
public async Task<IHttpActionResult> DeviceLogin(MyDevice device)
{
EnummyError myError = EnummyError.None;
// Authenticate Device.
myError = this.Authenticate(device);
// Perhaps Authenticate has an async method like this.
// myError = await this.AuthenticateAsync(device);
if (myError != EnummyError.None)
{
return ResponseMessage(Request.CreateResponse(Request.CreateResponse(HttpStatusCode.Forbidden, myError.ToString()));
}
}
The ResponseMessage() method creates a ResponseMessageResult under water. This class derives from IHttpActionResult and accepts a HttpResponseMessage as a parameter in the constructor (which is made by Request.CreateResponse()).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With