gpt4 book ai didi

c# - Azure函数: StatusCode cannot be set because the response has already started

转载 作者:行者123 更新时间:2023-12-03 07:02:16 27 4
gpt4 key购买 nike

我正在尝试从我的 Azure Function 流式传输数据,一切正常,但在执行后出现错误。

这是代码:

[FunctionName("QueryData")]
public async Task QuerySingleMessages([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req)
{
var message = await req.GetPostMessage<Message>();

var response = req.HttpContext.Response;
response.StatusCode = 200;
response.ContentType = "application/json-data-stream";

var sw = new StreamWriter(response.Body);

foreach (var msg in this.messageReaderService.FindLatestMessages(message.keys))
{
var json = System.Text.Json.JsonSerializer.Serialize(
msg,
new JsonSerializerOptions {PropertyNameCaseInsensitive = false});
await sw.WriteAsync(json);
}

await sw.FlushAsync();
await sw.DisposeAsync();
}

这是错误:

[2022-05-06T15:15:17.034Z] Executed 'QueryData' (Succeeded, Id=df70d5a7-37d7-40ef-b446-ecceb943e454, Duration=1350ms)
[2022-05-06T15:15:17.047Z] An unhandled host error has occurred.
[2022-05-06T15:15:17.048Z] Microsoft.AspNetCore.Server.Kestrel.Core: StatusCode cannot be set because the response has already started.

是否可以更改配置(或其他内容)以便阻止主机错误发生?

谢谢

最佳答案

从我们的末端复制之后,当我们尝试修复返回类型并返回 EmptyResult 即 return new EmptyResult(); 时,我们就能够完成这项工作。

[FunctionName("Function1")]
public static async Task<EmptyResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
var message = await req.GetPostMessage<Message>();

var response = req.HttpContext.Response;
response.StatusCode = 200;
response.ContentType = "application/json-data-stream";

var sw = new StreamWriter(response.Body);

foreach (var msg in this.messageReaderService.FindLatestMessages(message.keys))
{
var json = System.Text.Json.JsonSerializer.Serialize(
msg,
new JsonSerializerOptions { PropertyNameCaseInsensitive = false });
await sw.WriteAsync(json);
}

await sw.FlushAsync();
await sw.DisposeAsync();

return new EmptyResult();
}

关于c# - Azure函数: StatusCode cannot be set because the response has already started,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72143938/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com