Can a client cancel a Web Api request?

若如初见. 提交于 2019-12-12 16:26:19

问题


I have the following method in my web api controller (the long running methods honor cancellation tokens, i.e. they won't run if cancellation has been requested):

public async Task<IHttpActionResult> ApiMethod(CancellationToken cancellationToken)
{
    await LongRunningNetworkOperation1(cancellationToken);
    await LongRunningNetworkOperation2(cancellationToken);

    return Ok();
}

The client has the following code to call my web api controller:

using (var httpClient = new HttpClient())
{
    httpClient.Timeout = TimeSpan.FromMilliseconds(3000);

    try
    {
        // Sending DELETE request
        HttpResponseMessage deleteMessage = await httpClient.
                             DeleteAsync("http://localhost:80/api/apiMethod");
    }
    catch (Exception e)
    {
        // Timeout occurred.
    }
}

If the client's request times out before "LongRunningNetworkOperation2" is called, will the cancellationToken prevent "LongRunningNetworkOperation2" from running? In other word's, can the client signal the web api to stop running a certain request?


回答1:


can the client signal the web api to stop running a certain request?

In theory, yes. A cancellation of the HttpClient should close the underlying TCP/IP connection. In response, the ASP.NET stack should detect the loss of its client, and cancel the WebAPI CancellationToken.

In practice, it depends on how complete the HttpClient and WebAPI implementations are that you're using. Cancellation isn't necessarily guaranteed, but I expect it would work at least for the desktop HttpClient.



来源:https://stackoverflow.com/questions/36586632/can-a-client-cancel-a-web-api-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!