在 Azure Functions Http 触发器上设置 UTF-8 编码

Set UTF-8 Encoding on Azure Functions Http Trigger

编辑 以防我误诊, 以下是发送内容的示例: T6NLmFUZdYYdvhxmq67WD/TiShKbE0rK0xdHXJGo5sVx9/CrmBTViiQxjqLEQN66HkAUB9LvXW6C55maPLMd7u2cwNc8OlNuPTvZfx63Aawso/2mvewXQauUytGZ1Q8D

以及收到的内容: T6NLmFUZdYYdvhxmq67WD%2fTiShKbE0rK0xdHXJGo5sVx9%2fCrmBTViiQxjqLEQN66HkAUB9LvXW6C55maPLMd7u2cwNc8OlNuPTvZfx63Aawso%2f2mvewXQauUytGZ1Q8D

“%2”而不是反斜杠是我所说内容的最好例子

EDIT2 对于那些后来者:上传处理程序 raw 成功了,并修复了它。但是,如果您随后希望能够访问服务器回复,则需要创建一个下载处理程序。对于文本,使用 DownloadHandlerBuffer,例如

www.downloadHandler = new DownloadHandlerBuffer();

然后一旦你发送了请求,使用它来获得一个字符串响应:

string response = System.Text.Encoding.UTF8.GetString(www.downloadHandler.data);

我正在使用 Unity 的 UnityWebRequest 向 Azure 函数 HttpTrigger 类型功能发送 REST 调用。

现在,这两个函数都不公开字节,它们在后端公开字节并交给我字符串。 但是,当我的函数接收我的数据时,它包含很多转义字符,我认为它没有正确编码。我不确定如何正确编码它,考虑到我不能将我的字符串转换为带 UTF8.GetBytes 的 byte[],反之亦然。

如果重复,我深表歉意,我搜索过但找不到足够相似的问题。

在此处查看 unity 和 azure 代码:https://pastebin.com/pE4dYSfF

//UNITY SIDE
IEnumerator Foo()
    {
        var N = JSON.Parse("{}");
        N["input1"] = input1.text;
        N["input2"] = input2.text;
        string encrypted = Encrypt(N.ToString(), GenerateEncryptionKey);

        print("ENSEND: \n" + encrypted);
        using (UnityWebRequest www = UnityWebRequest.Post(targetURL, encrypted))
        {
            yield return www.SendWebRequest();

            if (www.isHttpError || www.isNetworkError)
            {
                Debug.LogError(www.error + "\n" + www.downloadHandler.text);
                onFail?.Invoke();
            }
            else
            {
                onSuccess?.Invoke();
                print(www.responseCode + " : " + www.downloadHandler.text);
            }

        }
        yield break;
    }

//FUNCTION SIDE 
[FunctionName("UserAuthentication")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            try
            {
                requestBody = Decrypt(requestBody, "Dracon");
            } catch (Exception e)
            {
//Throwing exception here due to escaped characters
                return new BadRequestObjectResult(e.Message + "\n" + requestBody + "\n" + Regex.Unescape(requestBody));
            }

            JSONNode N = null;
            try
            {
                N = JSON.Parse(requestBody);
                if (N["input1"] != "")
                {
                    name = N["username"];
                    return (ActionResult)new OkObjectResult($"Hello, {name}");
                } else if (name != "")
                {
                    return (ActionResult)new OkObjectResult($"Hello, {name}");
                } else
                {
                    return new BadRequestObjectResult("Invalid object syntax");
                }
            } catch (Exception e)
            {
                return new BadRequestObjectResult("Invalid JSON provided. N = " + (N != null).ToString() + "\n" + requestBody + "\n" + e.Message);
            }
        }

我看到您的 Unity 端有一个 Encrypt 函数,您的 Azure 函数端有一个 Decrypt 函数。

所以,你需要判断加密后的内容是否都是正常字符。如果是普通字符,你可以尝试设置Content-Type如下:

using (UnityWebRequest www = UnityWebRequest.Post(targetURL, encrypted))
{
    www.SetRequestHeader("Content-Type", "text/plain; charset=UTF-8");
    yield return www.SendWebRequest();

    if (www.isHttpError || www.isNetworkError)
    {
        Debug.LogError(www.error + "\n" + www.downloadHandler.text);
        onFail?.Invoke();
    }
    else
    {
        onSuccess?.Invoke();
        print(www.responseCode + " : " + www.downloadHandler.text);
    }

}

www.SetRequestHeader("Content-Type", "text/plain; charset=UTF-8"); 将确保所有字节都以 utf-8 编码。

但是,如果有一些特殊字符,我建议您将Content-Type设置为application/octet-stream。这样,Azure 函数将只为您保留请求正文的所有字节。


使用UploadHandlerRaw

using (UnityWebRequest www = new UnityWebRequest(url,"POST"))
{
    byte[] body = Encoding.UTF8.GetBytes(encrypted);
    www.uploadHandler = new UploadHandlerRaw(body);
    www.SetRequestHeader("Content-Type", "text/plain; charset=UTF-8");
    yield return www.SendWebRequest();

    if (www.isHttpError || www.isNetworkError)
    {
        Debug.LogError(www.error + "\n" + www.downloadHandler.text);
        onFail?.Invoke();
    }
    else
    {
        onSuccess?.Invoke();
        print(www.responseCode + " : " + www.downloadHandler.text);
    }

}