Web API action parameter is intermittently null

梦想与她 提交于 2019-12-05 13:26:53
gooid

I'm still investigating the root cause of this but so far my gut feeling is that ContinueWith() is being executed in a different context, or at a point by which the request stream has been disposed or something like that (once I figure that out for sure I will update this paragraph).

In terms of fixes, I've quickly road tested three that can handle 500 requests with no errors.

The simplest is to just use task.Result, this does however have some issues (it can apparently cause deadlocks, although YMMV).

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
    var result = request.Content.ReadAsStringAsync().Result;
    return base.SendAsync(request, cancellationToken);
}

Next, you can ensure you are properly chaining your continuations to avoid any ambiguity about context, it is however quite ugly (and I'm not 100% sure if it is side effect free):

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
    var result = request.Content.ReadAsStringAsync().ContinueWith(task =>
    {
        /* do stuff with task.Result */
    });

    return result.ContinueWith(t => base.SendAsync(request, cancellationToken)).Unwrap();
}

Finally, the optimal solution appears to make use of async/await to sweep away any threading nasties, obviously this may be an issue if you are stuck on .NET 4.0.

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
    var content = await request.Content.ReadAsStringAsync();
    Debug.WriteLine(content);
    return await base.SendAsync(request, cancellationToken);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!