Web Api请求引发“将内容复制到流时出错".

问题描述:

我正在尝试实现此代码示例,但得到 HttpRequestException -"将内容复制到流中时发生错误."调用 ReadAsStringAsync()方法时.内部的例外是"无法访问已处置的对象".我正在使用Fiddler发出请求.我不明白有人可以解释为什么我遇到此异常并提供解决方案吗?

I'm trying to implement this code example, but get a HttpRequestException - "Error while copying content to a stream." when the ReadAsStringAsync() method is called. The inner exception is "Cannot access a disposed object." I'm using Fiddler to make the request. I don't understand. Can someone explain why I'm getting this exception and offer a solution?

Web Api方法:

Web Api Method:

public async Task<HttpResponseMessage> Post(HttpRequestMessage request)
{
    try
    {
        var jsonString = await request.Content.ReadAsStringAsync();
    }
    catch (Exception ex)
    {                
        throw;
    }
    return new HttpResponseMessage(HttpStatusCode.Created);
}

提琴手(POST):

User-Agent: Fiddler
Host: localhost:23567
Content-Length: 18
Content-Type: application/json; charset=utf-8
Body{"Test":1}

我有一个线索,但需要验证.在Web Api控制器上,我有一个 ActionFilterAttribute ,在其 OnActionExecuting 覆盖中,有以下一行:

I have a clue, but need verification. On the Web Api controller, I have an ActionFilterAttribute and in its OnActionExecuting override, there's this line:

public override async void OnActionExecuting(HttpActionContext actionContext)
{
    // omitted code
    actionContext.Request.Content.ReadAsStreamAsync();
}

可能是因为这里读取了内容,所以不再可用了吗?如果是这样,如何在方法中使用它?这里的内容与HttpRequestMessage相同吗?可能包含一个答案.

Could it be that because the Content is read here, it's not available again? If so, how can I make it available in the method? Is the Content here the same as the HttpRequestMessage? This may contain an answer.

由于控制器的 ActionFilterAttribute的 OnActionExecuting 方法正在调用 ReadAsStreamAsync ,因此内容无法再次读取.我将 ReadAsStreamAsync 更改为 ReadAsStringAsync ,请求的内容在控制器中可用.显然,ReadAsStringAsync会缓冲内容,使其仍然可用.此链接提供了答案.

Because the controller's ActionFilterAttribute's OnActionExecuting method is calling ReadAsStreamAsync, the Content can't be read again. I changed ReadAsStreamAsync to ReadAsStringAsync and the request's Content is available in the controller. Apparantly, ReadAsStringAsync buffers the Content so it's still available. This link provided the answer.