使用异步/等待和返回任务< Htt的presponseMessage>从的ASP.NET Web API方法任务、方法、Htt、presponseMessage

2023-09-04 22:41:20 作者:朕好萌!

我有一个可移植类库(PCL)的方法是这样的:

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();
    }
}

我的ASP.NET Web API方法是这样的:

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;
}

什么是返回任务中的Web API的影响。这可以吗?我想用计谋的唯一原因是这样我就可以使用便携式类库(PCL)。什么是最好的做法是什么?我应该有一个syncronous版本,我的方法和asyncronous版本?有哪些表现及code可读性和可维护性的影响?

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?

也我也有同样的效果,如果我回到任务&LT;字符串&GT; ,而不是任务&LT; Htt的presponseMessage&GT;

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

推荐答案

异步和等待在ASP.NET完全可以接受的。这里有一个斯科特Handselman视频demoing它: http://www.asp.net / vnext /概述/ ASPNET /异步和 - 计谋

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

还我有同样的效果,如果我回到任务&LT;字符串&GT; ,而不是任务&LT; Htt的presponseMessage&GT;

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

不是真的知道你的意思。任务就像一个容器中的对象,所以任务&LT;字符串&GT; 将包含您的字符串结果和任务&LT; Htt的presponseMessage&GT; 将包含您的Htt presponseMessage结果......那是什么意思?我认为这两种方法是完全可以接受的。如果你只需要字符串,然后再与这一点。没有点返回比你更需要。

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.