我正在呼叫一些長期運行的服務并使用 Azure Relay 來訪問它們。問題是 Azure 中繼需要在 60 秒內做出回應,否則我會收到 504 超時。我確實想要一個實際的超時(2 分鐘)。
我試圖通過以下 3 個任務來解決這個問題:
- 啟動遞回任務并
" "每 10 秒發送一次資料 ( ) WhenAny與 2 個任務一起使用;我的實際服務電話和Task.Delay(120000)- 等到步驟#2 中的任務之一完成并取消遞回#1 任務。
- 如果完成的任務是我的實際任務,則回傳結果。否則回傳 504 超時。
當我用 <10 秒測驗它時,一切正常。如果我用 > 10 秒測驗它,我會得到:
The HTTP status code, status description, and headers cannot be modified after writing to the output stream.
我是新手,我認為我的代碼存在一些基本問題,而該錯誤只是其中的產物。
[HttpGet(Name = "GetNameAndDateTimeDelayKeepAlive")]
public async Task<ActionResult<string>> GetNameAndDateTimeDelayKeepAlive([FromQuery, DefaultValue(20)] int seconds)
{
var cts = new CancellationTokenSource();
var mainTask = _client.GetNameAndDateTimeDelayKeepAlive(seconds);
// Start a recursive task that will send a " " every 10 seconds to the response stream
var keepAliveTask = Task.Run(() => KeepAliveLoop(cts.Token));
// Arbitrary 2 min MAX timeout
var response = await Task.WhenAny(mainTask, Task.Delay(120000)).ConfigureAwait(true);
// Cancel the keep alive loop
cts.Cancel();
// Task completed within the alloted timeout
if (response == mainTask)
{
return Ok(mainTask.Result.response);
}
// If we're here then task didn't complete in 2 min timeout
return new ObjectResult(this) { Value = "504 Gateway Timeout", StatusCode = 504 };
}
protected async Task KeepAliveLoop(CancellationToken ct)
{
if (!ct.IsCancellationRequested)
{
// Wait 10 seconds
await Task.Delay(10000);
// Write " " to the response stream to keep connection alive
StreamWriter sw;
await using ((sw = new StreamWriter(Response.Body)).ConfigureAwait(false))
{
await sw.WriteLineAsync(" ").ConfigureAwait(false);
await sw.FlushAsync().ConfigureAwait(false);
}
// Call self to loop
await KeepAliveLoop(ct);
}
}
uj5u.com熱心網友回復:
您不能將這種流式傳輸與ActionResult.
ActionResult是一個完整的 HTTP 回應,包括狀態碼、標頭和正文。但是,流式傳輸(即寫入Response.Body)是通過寫入主體來完成的。為了撰寫正文,狀態代碼/標頭必須都已發送。
因此,只要您的代碼開始寫入Response.Body,ASP.NET 就會寫出狀態代碼/標頭。然后當你的代碼回傳時ActionResult,它會嘗試寫出狀態碼、標題和正文;你會得到一個例外,說狀態代碼/標題已經被寫入。
ActionResult我知道的唯一解決方案是不要在Ok寫入. 您必須自己對回應進行序列化并將其寫入。ObjectResultResponse.BodyResponse.Body
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/517398.html
