req.Content.ReadAsStringAsync()。从浏览器访问时结果始终返回null(但不在Azure门户中)

问题描述 投票:1回答:2

下面包含我的完整代码(Azure门户上的Azure功能应用程序)。要特别注意这两条线。

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

当我使用右侧面板下的请求体测试函数时,jsonContent将按原样打印在日志中。但是,在浏览器中使用函数url并使用&name=azure附加它,jsonContent为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-functions azureportal httpresponsemessage
2个回答
1
投票

当您使用&name=azure在浏览器中附加功能URL时,它会将name = azure设置为http请求标头。因此,如果您要使用请求正文发送http请求,则可以使用postman来触发Azure功能。

这是我的测试:enter image description here enter image description here


0
投票

作为查询追加与使用请求正文不同。你可以像Python一样在Python中调用函数和请求体(只是一个例子):

reqBody = {
        'customerid' : customerid,
        'imgdata' : imgdata
    }
headers = {
        'Content-Type': 'application/json',
    }
url = "https://xxxxx.azurewebsites.net/api/HTTPTrigger.............."
response = requests.post(url, headers=headers,
                             data=json.dumps(reqBody))
print(response.json())
© www.soinside.com 2019 - 2024. All rights reserved.