首页 > 解决方案 > 从浏览器访问时,req.Content.ReadAsStringAsync().Result 始终返回 null(但在 Azure 门户中没有)

问题描述

下面包含我的完整代码(Azure 门户上的 Azure Function App)。请特别注意这两行。

var jsonContent = req.Content.ReadAsStringAsync().Result; log.LogInformation("jsonContent" + jsonContent);

当我使用右侧面板下的请求正文测试该功能jsonContent时,它会按原样打印在日志中。但是,在浏览器中使用函数 url并将其附加&name=azurejsonContent则为 null,如日志中所示。

//full code
#r "Newtonsoft.Json"
using System.Net;
using Newtonsoft.Json;
using System.Text;

using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, ILogger log)
{
    // these two lines are problematic???
    var jsonContent = req.Content.ReadAsStringAsync().Result;
    log.LogInformation("jsonContent" + jsonContent);

    // you can ignore the following lines (not related to question)
    string jsonToReturn = "Hello World";

    return new HttpResponseMessage(HttpStatusCode.OK) {
        Content = new StringContent(jsonToReturn, Encoding.UTF8, "application/json")
    };
}

我尝试将线路更改为此,但它也没有工作。

var jsonContent = await req.Content.ReadAsStringAsync().Result;

错误类似于

'string' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)

无论如何,我知道一个解决方法是使用HttpRequest而不是HttpRequestMessage生成jsonContent,但我只是好奇为什么这个案例不起作用。

谁能发现我的错误?谢谢!

标签: azure-functionsazureportalhttpresponsemessage

解决方案


当您在浏览器中附加函数 url 时&name=azure,它会将name=azure 设置为 http 请求标头。所以,如果你想发送带有请求体的 http 请求,你可以使用postman来触发 Azure Function。

这是我的测试: 在此处输入图像描述 在此处输入图像描述


推荐阅读