从async返回StringContent

时间:2016-08-31 23:26:08

标签: c# asp.net-web-api2

如何从异步中返回StringContent?我还需要将其作为任务返回吗?以下是我正在使用的示例代码:

public async Task<HttpResponseMessage> GetOrder(string url)
{
    xml = "<result><success> True </success><message></result>";

    responseMessage = await httpContent;
    return new  HttpResponseMessage()
    {
        Content = new StringContent(xml, Encoding.UTF8, "application/xml")
    };    
}

2 个答案:

答案 0 :(得分:2)

如果您实际上没有使用async/await,那么该方法将如下所示。

public Task<HttpResponseMessage> GetOrder(string url) {
    xml = "<result><success> True </success><message></result>";

    var responseMessage = new  HttpResponseMessage() {
        Content = new StringContent(xml, Encoding.UTF8, "application/xml")
    }; 

    return Task.FromResult(responseMessage);   
}

答案 1 :(得分:1)

这是你想要做的吗?

   public async Task<HttpResponseMessage> GetOrder(string url)
    {
        string xml = "<result><success> True </success><message></result>";

        return await Task<HttpResponseMessage>.Factory.StartNew(() => new HttpResponseMessage()
                                                    {
                                                        Content = new StringContent(xml, Encoding.UTF8, "application/xml")
                                                    });

    }

如果是这样,您的返回xml也无效。引用许多在线xml验证器之一“元素类型”消息“必须由匹配的结束标记终止”(消息)