簡體   English   中英

如何在 ASP.NET Web ZDB974238714CA8DE634A7CE1D083A 中的 Controller 操作中處理取消?

[英]How to handle cancellation in Controller actions in ASP.NET Web API?

我正在使用 Asp.Net Core 開發 Web API。

我試圖找出在服務器端處理取消的最佳方法。

我通常有一個服務層並在服務中實現一個 try-catch 塊。

本文中,建議實現一個 Controller 操作過濾器,它將捕獲服務中的所有 OperationCanceledExceptions 並返回狀態碼 400。

public class OperationCancelledExceptionFilter : ExceptionFilterAttribute
{
    private readonly ILogger _logger;

    public OperationCancelledExceptionFilter(ILoggerFactory loggerFactory)
    {
        _logger = loggerFactory.CreateLogger<OperationCancelledExceptionFilter>();
    }
    public override void OnException(ExceptionContext context)
    {
        if(context.Exception is OperationCanceledException)
        {
            _logger.LogInformation("Request was cancelled");
            context.ExceptionHandled = true;
            context.Result = new StatusCodeResult(400);
        }
    }
}

這意味着我不會在服務層捕獲這個異常,而是讓它到達 controller 動作。

這是你能想到的最好的方法嗎? 你有更好的建議方法嗎?

CancellationToken通常用於此作業。

例如;

config.MessageHandlers.Add(new CancelledTaskBugWorkaroundMessageHandler());

class CancelledTaskBugWorkaroundMessageHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        HttpResponseMessage response = await base.SendAsync(request, cancellationToken);

        // Try to suppress response content when the cancellation token has fired; ASP.NET will log to the Application event log if there's content in this case.
        if (cancellationToken.IsCancellationRequested)
        {
            return BadRequest();
        }

        return response;
    }
}

或者;

app.Use(async (ctx, next) =>
{
    try
    {
        await next();
    }
    catch (OperationCanceledException)
    {
    }
});

我希望這會有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM