You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure Functions独立进程中如何设置请求编码为UTF-8?

在Azure Functions独立进程模式下设置请求体UTF-8编码

由于你使用的是Azure Functions独立进程模式,该模式基于ASP.NET Core框架,常规ASP.NET的<system.web>配置不再适用,以下是两种可行的解决方案:

方案1:手动读取请求体时指定UTF-8编码

直接在读取请求体流时,通过StreamReader明确指定UTF-8编码,确保读取内容的编码符合要求:

public static async Task<IActionResult> RunAsync(
    [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
    ILogger log)
{
    // 重置流位置到起始处(避免之前的读取操作导致流指针偏移)
    req.Body.Position = 0;
    
    // 使用UTF-8编码读取请求体
    using var reader = new StreamReader(req.Body, Encoding.UTF8);
    string requestBody = await reader.ReadToEndAsync();
    
    // 后续业务逻辑处理
    log.LogInformation("读取到请求体: {RequestBody}", requestBody);
    
    return new OkObjectResult("处理完成");
}

方案2:全局配置强制使用UTF-8编码

如果希望所有HTTP触发的函数都默认使用UTF-8编码处理请求,可以在Program.cs中添加全局配置:

var builder = WebApplication.CreateBuilder(args);

// 配置JSON输入编码为UTF-8
builder.Services.Configure<Microsoft.AspNetCore.Http.Json.JsonOptions>(options =>
{
    options.InputEncoding = Encoding.UTF8;
});

// 添加函数服务
builder.Services.AddAzureFunctions();

var app = builder.Build();

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapAzureFunctions();

app.Run();

如果存在请求头未指定Content-Type: application/json; charset=utf-8的情况,还可以添加中间件强制覆盖请求的编码设置:

// 在Program.cs的app.MapAzureFunctions()之前添加中间件
app.Use(async (context, next) =>
{
    // 强制设置请求编码为UTF-8
    context.Request.ContentType = "application/json; charset=utf-8";
    await next();
});

内容的提问来源于stack exchange,提问作者user2503480

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 16:10:04