11

I have a Portable Class Library (PCL) method like this:

public async Task<string> GetLineStatuses()
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
    using (HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync())
    {
        return response.GetResponseStream().ReadAllText();
    }
}

My ASP.NET Web Api method looks like this:

public async Task<HttpResponseMessage> Get()
{
    HttpResponseMessage response = new HttpResponseMessage();
    string statuses = await service.GetStatuses();
    response.Content = new StringContent(statuses);
    return response;
}

What are the implications of returning a Task in Web API. Is this allowed? The only reason I want to use await is so I can use a Portable Class Library (PCL). What is the best practice? Should I have a syncronous version of my method and an asyncronous version? What are the performance and code readability and maintainability implications?

Also would I have the same effect if I returned Task<string> rather than Task<HttpResponseMessage>?

2
  • 1
    I belive ASP.NET in .Net 4.5 does support async methods, so your code should work fin. Why are you asking if this is allowed? Didn't you try it out? Commented Dec 28, 2012 at 13:05
  • I also want to know what the performance and code readability and maintainability implications? Commented Feb 25, 2015 at 9:13

2 Answers 2

5

Async and await are perfectly acceptable in ASP.NET. Here's a Scott Handselman video demoing it: http://www.asp.net/vnext/overview/aspnet/async-and-await

"Also would I have the same effect if I returned Task<string> rather than Task<HttpResponseMessage>?"

Not really sure what you mean by this. The Task is like a container for the object, so a Task<string> would contain your string result and a Task<HttpResponseMessage> would contain your HttpResponseMessage result... Is that what you mean? I think either method is perfectly acceptable. If you just need the string, then go with that. No point in returning more than you need.

Sign up to request clarification or add additional context in comments.

3 Comments

In Web API, you can return any object you want to be serialized as the content or return a HttpResponseMessage. Thats what I meant.
I'm still not following you. Keep in mind, it's not returning a string, but a Task<string>. The string, in Task<string>.Result can be rendered as content, but a Task<string> itself cannot.
Returning a string and returning an HttpResponseMessage with a StringContent and two different things. If you return a string, WebAPi will use content negotiation to find a formatter that can serialize that string. If you return a StringContent, that string goes out directly in the response. But returning a Task<string> that completes eventually with a string should be equivalent to returning that string directly as far as WebAPI is concerned.
2

as alternative:

public static async Task<string> CallGET(string requestUri, string id = "")
{
    string responseData;
    using (var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true }))
    {
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        Uri.TryCreate(new Uri(baseURI), $"{requestUri}{(string.IsNullOrEmpty(id) ? string.Empty : $"/{id}")}", out Uri fullRequestUri);
        using (var response = await client.GetAsync(fullRequestUri))
        {
            responseData = await response.Content.ReadAsStringAsync();
        }
        return responseData;
    }
}

and call would be:

var getListUsersResult = Utils.CallGET($"/v1/users").Result;
var resultset= JsonConvert.DeserializeObject(getListUsersResult, typeof(List<UsersDTO>)) as List<UsersDTO>;
UserDTO r = users.Where(d => d.Name.ToLower().Contains("test")).FirstOrDefault();

and another call for one item:

var getUser = Utils.CallGET($"/v1/users", $"{USER_ID}").Result;
var getUserResponse = JsonConvert.DeserializeObject(getUser, typeof(UserDTO)) as UserDTO;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.